继续昨天的 post
两个实体
public class Realtor
{
public Realtor()
{
Guid = Guid.NewGuid();
Registration = DateTime.Now;
}
public int Id { get; set; }
public Guid Guid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Registration { get; set; }
public int SubdivId { get; set; }
public Subdiv Subdiv { get; set; }
}
public class Subdiv
{
public Subdiv()
{
Created = DateTime.Now;
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
public List<Realtor> Realtors { get; set; }
}
我花测试
- 我添加了一个 Subdiv (TOSTER TM) 并收到了他的 ID
接下来,我添加一个 Realtor 并推送在 ID 上找到的 Subdiv 属性,即新创建的 TOSTER TM Realtor.Subdiv 是 Subdiv 类型的对象。好的。
我们得到了 Subdiv 对象,这在上面的 Realtor 中是没有的,并且看到他的
List<Realtor> = null
请帮助解决这个问题。
最佳答案
试试这个:
Relator rl = Context.Relators.Include(r => r.Subdiv).First(s => s.Id == id);
现在您可以访问 Subdiv 属性
对于更多相关日期,您可以多次调用 Include 方法:
Relator rl = Context.Relators
.Include(r => r.Subdiv)
.Include(r => r.AnotherRel)
.First(s => s.Id == id);
对于具有多个深度级别的实体:
如果 Subdir 是一个集合
Relator rl = Context.Relators
.Include(r => r.Subdiv)
.ThenInclude(sub => sub.SecondLevelDepth)
.First(s => s.Id == id);
如果 Subdir 是一个实体
Relator rl = Context.Relators
.Include(r => r.Subdiv.Select(s => s.SecondLevelDepth)
.First(s => s.Id == id);
关于c# - Entity Framework Core 不保存相关数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40381914/