0
我正在用实体框架5编写C#(.NET 4.5)中的简单数据库应用程序。我遇到了一种情况,我可能或可能不需要加载单个实体的相关实体。如果碰巧需要加载实体的相关实体,我想急于加载相关实体的相关实体。基本上,我试图避免“SELECT N + 1”问题。希望下面的代码将使我想要做的事情明确:实体框架 - 渴望加载相关实体的相关实体
using (var ctx = new DbContext())
{
// Find a single instance of a person. I don't want to eagerly load
// the person's friends at this point because I may not need this
// information.
var person = ctx.Persons.Single(x => x.PersonID == 12);
// Many lines of code...
// Many lines of code...
// Many lines of code...
// Okay, if we have reached this point in the code, the person wants to
// send all his friends a postcard, so we need the person's friends and
// their addresses.
// I want to eagerly load the person's friends' addresses, but the Include
// method is not allowed. The property "Friends" is just an ObservableCollection.
var friends = person.Friends.Include("Address").ToList();
// So, I must do the following:
var friends = person.Friends.ToList();
// Now I will output the address of each friend. This is where I have the
// SELECT N+1 problem.
foreach(var friend in friends)
{
// Every time this line is executed a query (SELECT statement) is sent
// to the database.
Console.WriteLine(friend.Address.Street);
}
}
任何想法,我应该做什么?
谢谢一百万......这正是我所需要的。 – HydroPowerDeveloper 2013-05-11 02:50:01
@Slauma ...我终于搞定了......我需要添加“使用System.Data.Entity;”使其工作。再次感谢您的帮助......我真的很感激! =) – HydroPowerDeveloper 2013-05-11 03:16:51