c# - Entity Framework ObjectQuery.Include()

标签 c# entity-framework

我有一个对象,其中有两个对象作为属性(UserPrimaryNode),两者都可能为空,见下文:

public class Item
{
    [Key]
    public int ItemId { get; set; }
    public string ItemName { get; set; }
    public Node PrimaryNode { get; set; }
    public User User { get; set; }
}

我正在使用 Entity Framework 6 来填充 Item 对象,并使用链式包含来填充其中的 PrimaryNodeUser 对象。

当第一个链式包含有一个空对象时,整个对象返回为空,例如:

using (var db = new MyContext())
{
    var item = db.Items.Include(i => i.User).Include(n => n.PrimaryNode).FirstOrDefault(i => i.ItemId == id);
}

如果在上面的示例中 i.User 为空,则 item 变量为空。填充两个子对象的最佳方式是什么,如果一个子对象为 null,则父对象和另一个子对象仍将被填充?

最佳答案

我认为您的问题不是由 Include 调用引起的。根据documentation :

This extension method calls the Include(String) method of the IQueryable source object, if such a method exists. If the source IQueryable does not have a matching method, then this method does nothing.

换句话说将被翻译成:

 var item = db.Items.Include("User").Include("PrimaryNode").FirstOrDefault(i => i.ItemId == id);

我的问题是,您确定您有一个 Item,该 ID 与 UsersPrimaryNodes 表中的现有行正确关联D B?。当您在最后调用 Include 方法时将被转换为一个连接,因此如果您关系的 FK 与引用的 PK 不匹配,您的查询不应返回您所期望的.

无论如何,如果你想尝试另一种变体来加载相关属性,你可以使用 Explicit Loading :

var item = db.Items.FirstOrDefault(i => i.ItemId == id);
context.Entry(item).Reference(p => p.PrimaryNode).Load(); 
context.Entry(item).Reference(p => p.User).Load();

关于c# - Entity Framework ObjectQuery.Include(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34640034/

相关文章:

c# - EF AddOrUpdate 种子不更新子实体

c# - 如何使Entity Framework生成的类实现INotifyPropertyChanged?

entity-framework - 默认目标 Entity Framework 版本需要 edmx 架构版本 2.0.0.0 或更低版本。指定的架构是版本 3.0.0.0

C# Entity Framework 分页

entity-framework - 使用 EF Core 记录查询持续时间

c# - 使用 mvvm light 实现文件计数器

c# - 如何在.net中实现和扩展Joshua的 builder 模式?

c# - 阻塞函数调用的看门狗

c# - Asp.net 和 C# 错误 : The name "mygv" does not exist in the current context

c# - Entity Framework 错误 - 查询语法无效