EF 核心导航 属性 return 即使在使用 Incude 后仍为空值
EF core navigation property return null value even after using Incude
这不是一个重复的问题,因为我查了很多问题,包括,这是最接近我想要的但没有解决挑战。
我的 table 模型关系是这样设置的:
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 的事务 table,并在保存时采用正确的值。
但是当我使用用户 Id
获取时
User user = dbcontext.Set<User>().Include(t => t.Transactions).FirstOrDefault(u => u.UserId == userId);
user.Transactions
有一个全部为 null 的交易列表 Transaction.Patient
这里到底发生了什么,我该如何克服它?
谢谢。
您正在嵌套导航。因此,您必须像这样使用 ThenInclude
来添加 Patient
,这是 Transaction
.
的导航 属性
User user = dbcontext.Set<User>().Include(t => t.Transactions).ThenInclude(p => p.Patient).FirstOrDefault(u => u.UserId == userId);
这不是一个重复的问题,因为我查了很多问题,包括
我的 table 模型关系是这样设置的:
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 的事务 table,并在保存时采用正确的值。 但是当我使用用户 Id
获取时User user = dbcontext.Set<User>().Include(t => t.Transactions).FirstOrDefault(u => u.UserId == userId);
user.Transactions
有一个全部为 null 的交易列表 Transaction.Patient
这里到底发生了什么,我该如何克服它? 谢谢。
您正在嵌套导航。因此,您必须像这样使用 ThenInclude
来添加 Patient
,这是 Transaction
.
User user = dbcontext.Set<User>().Include(t => t.Transactions).ThenInclude(p => p.Patient).FirstOrDefault(u => u.UserId == userId);