【问题标题】:EF core navigation property return null value even after using Incude即使在使用 Incude 之后,EF 核心导航属性也会返回空值
【发布时间】:2021-04-05 22:53:48
【问题描述】:

这不是重复的问题,因为我查了很多问题,包括 this,这是最接近我想要的但没有解决挑战的问题。

我的表模型关系是这样设置的:

public class User
{
    public long UserId { get; set; }
    public string Name { get; set; }
    public IList<Transaction> Transactions { get; set; }
}

public class Transaction
{
    public long TransactionId { get; set; }
    public User User { get; set; }
    public User Patient { get; set; }
}

实体的流畅 api 设置

//some other modelbuilder stuff
modelBuilder.Entity<User>(entity => 
{
  entity.HasMany(e => e.Transactions).WithOne(e => e.User);
  //wanted to add another entity.HasMany(e => e.User).WithOne(e => e.Patient) but efcore didn't allow me.
});

这会生成一个带有 UserUserId 和 PatientUserId 的 Transaction 表,并在保存时采用正确的值。 但是当我使用用户 ID 进行获取时

User user = dbcontext.Set<User>().Include(t => t.Transactions).FirstOrDefault(u => u.UserId == userId);

user.Transactions 有一个交易列表全部为空Transaction.Patient

这里到底发生了什么,我该如何克服它? 谢谢。

【问题讨论】:

    标签: c# entity-framework orm entity-framework-core


    【解决方案1】:

    您正在嵌套导航。因此,您必须像这样使用ThenInclude 来添加Patient,这是Transaction 的导航属性。

    User user = dbcontext.Set<User>().Include(t => t.Transactions).ThenInclude(p => p.Patient).FirstOrDefault(u => u.UserId == userId);
    

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 2017-10-01
      • 2011-07-16
      • 2019-01-05
      相关资源
      最近更新 更多