0

我正在使用 Entity Framework 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);

    }

}

关于我应该做什么的任何想法?

4

1 回答 1

1

这是显式加载的好情况- 除了急切和延迟加载之外,使用 Entity Framework 加载相关实体的第三个选项:

using (var ctx = new DbContext())
{
    var person = ctx.Persons.Single(x => x.PersonID == 12);

    // ...

    // the following issues one single DB query
    person.Friends = ctx.Entry(person).Collection(p => p.Friends).Query()
        .Include(f => f.Address) // = .Include("Address")
        .ToList();

    foreach(var friend in person.Friends)
    {
        // No DB query because all friends including addresses
        // have already been loaded
        Console.WriteLine(friend.Address.Street);
    }
}

这里的关键是.Query()它返回一个可查询的Friends集合,并允许您为朋友集合添加任意额外的查询逻辑——比如过滤、排序、加入额外的相关数据(= Include)、聚合(Count例如朋友)等。

于 2013-05-10T21:37:38.967 回答