【问题标题】:Query child records using entity framework使用实体框架查询子记录
【发布时间】:2014-10-13 18:24:10
【问题描述】:

这是我的 edmx 图。

我正在尝试获取特定 ProfileId 的所有驱动器

这是我写的查询

var prof = (from p in pe.UserDrives.Include("Drive")
                    where p.ProfileId == Cuser.ProfileId
                    select p).ToList();

数据:

Drive

Id  googleAccount   RefreshToken    AccessToken
1   Cloud            NULL            NULL
2   Storage          NULL            NULL

UserDrive
DriveId Id  ProfileId
1        1  1
2        2  1

我会得到的结果是 profileId =1 的驱动器信息将是来自 userdrive 的 2 条记录及其相应的驱动器信息

相反,我希望对于选定的配置文件有一个驱动记录列表

请回答新手问题。我只是在学习

【问题讨论】:

    标签: sql-server entity-framework asp.net-mvc-5 entity-framework-6


    【解决方案1】:

    您只需选择Drive 属性而不是UserDrive。像这样:

    var prof = (from p in pe.UserDrives.Include("Drive")
                        where p.ProfileId == Cuser.ProfileId
                        select p.Drive).ToList();
    

    【讨论】:

    • 使用您使用的语法和@anurag 在他的回答中写的内容是否有任何性能差异。我只是在学习,想知道最佳实践。谢谢你的回答有效
    • 如果有的话,他的速度可能会慢一些,因为他也在拉入 Profile 表。如果不是这样,我会说差异可能可以忽略不计。顺便说一句,当您创建上下文时,您可以在 context.Database.Log = s => Debug.WriteLine(s); 之后添加一行,以查看生成的实际查询以及执行时间。
    • 我通常将该行包装在 #if DEBUG 中,以消除登录生产环境对性能的影响。
    • 感谢您的解释。将按照您的建议尝试#if DEBUG
    【解决方案2】:

    请试一试

    var prof = (from p in Profile
                  join ud in UserDrive on p.id equals ud.profileId
                  join d in drive on ud.driveid equals d.Id
                  where p.ProfileId == Cuser.ProfileId
                  select new { p,ud,d}).tolist();
    string a = prof.p.columnname;
    string b = prof.ud.columnname;
    string c = prof.d.columnname;
    

    【讨论】:

    • 使用您使用的语法和@pquest 在他的回答中写的内容是否有任何性能差异。我只是在学习,想知道最佳实践。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多