C# EF核心导航属性即使在使用Incude之后也返回空值
这不是一个重复的问题,因为我查了很多问题,包括,哪一个最接近我想要的,但没有解决挑战 我的表模型关系设置如下:C# EF核心导航属性即使在使用Incude之后也返回空值,c#,entity-framework,orm,entity-framework-core,C#,Entity Framework,Orm,Entity Framework Core,这不是一个重复的问题,因为我查了很多问题,包括,哪一个最接近我想要的,但没有解决挑战 我的表模型关系设置如下: public class User { public long UserId { get; set; } public string Name { get; set; } public IList<Transaction> Transactions { get; set; } } public class Transaction { pub
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; }
}
公共类用户
{
公共长用户标识{get;set;}
公共字符串名称{get;set;}
公共IList事务{get;set;}
}
公共类事务
{
公共长事务ID{get;set;}
公共用户{get;set;}
公共用户患者{get;set;}
}
实体的fluent 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.
});
//其他一些modelbuilder的东西
modelBuilder.Entity(Entity=>
{
entity.HasMany(e=>e.Transactions),其中一个(e=>e.User);
//想要添加另一个实体。HasMany(e=>e.User)。WithOne(e=>e.Patient),但efcore不允许。
});
这将生成一个具有userid和PatientUserId的事务表,并在保存时采用正确的值。
但当我使用用户Id执行get时
User user = dbcontext.Set<User>().Include(t => t.Transactions).FirstOrDefault(u => u.UserId == userId);
User User=dbcontext.Set().Include(t=>t.Transactions).FirstOrDefault(u=>u.UserId==UserId);
user.Transactions
有一个全部为空的事务列表transaction.Patient
这里到底发生了什么?我该如何度过?
谢谢。您正在嵌套导航。因此,您必须像这样使用
然后include
来添加患者
,这是事务
的导航属性
User user = dbcontext.Set<User>().Include(t => t.Transactions).ThenInclude(p => p.Patient).FirstOrDefault(u => u.UserId == userId);
User User=dbcontext.Set().Include(t=>t.Transactions)。然后Include(p=>p.Patient)。FirstOrDefault(u=>u.UserId==UserId);
有效!谢谢不客气。