【问题标题】:Entity Framework - Eager Load Related Entities' Related Entity实体框架 - 急切加载相关实体的相关实体
【发布时间】:2013-05-10 19:16:43
【问题描述】:

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

    }

}

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

【问题讨论】:

    标签: visual-studio-2012 entity-framework-5 sql-server-2012-express


    【解决方案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朋友)等

    【讨论】:

    • 谢谢一百万...这正是我所需要的。
    • @Slauma ...我终于让它工作了...我需要添加“使用 System.Data.Entity;”让它工作。再次感谢您的所有帮助......我真的很感激! =)
    猜你喜欢
    • 2011-04-09
    • 2012-02-07
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多