继续昨天的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; }
}
我花了考试
答案 0 :(得分:2)
问题不在于保存相关数据(应该正确保存,您可以检查数据库内部),但加载它。
EF Core目前不支持延迟加载,因此为了获取相关数据,您需要明确请求它(所谓的预先加载):
Realtor rl = context.Realtors.Include(r => r.Subdiv).First(r => r.Id == id);
有关详细信息,请参阅EF Core: Loading Related Data。
答案 1 :(得分:1)
试试这个:
Relator rl = Context.Relators.Include(r => r.Subdiv).First(s => s.Id == id);
现在您可以访问Subdiv属性
对于更多相关日期,您可以多次调用包含方法:
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);
答案 2 :(得分:1)
实体框架核心允许保存相关实体,您需要为主表和详细信息表定义Fluent API设置
public class Order
{
public int Id { get; set; }
public int AddressId { get; set; }
public string DeliveryNotes { get; set; }
public int PurchaseOrderNo { get; set; }
public virtual ICollection<OrderItem> Items { get; set; }
}
public class OrderItem
{
public int Id { get; set; }
public string ProductName { get; set; }
public int Quantity { get; set; }
public decimal UserPrice { get; set; }
public string Comment { get; set; }
[ForeignKey("OrderId ")]
public int OrderId { get; set; }
public virtual Order Order { get; set; }
}
在DBConext OnModelCreating方法中,定义关系,它将确保您何时拥有订单对象,其相关或子对象,即注册也将被保存
modelBuilder.Entity<Order>()
.HasMany(c => c.Items)
.WithOne(e => e.Order);
modelBuilder.Entity<OrderItem>().Ignore(x => x.Order);
现在你的代码应该是这样的
Order _order = new Order{ AddressId = 1, DeliveryNotes ="some notes", PurchaseOrderNo =1};
_order.Items = new List< OrderItem>();
_ordert.Items.add(new OrderItem{ ProductName =”Laptop”, Quantity =1, UserPrice =1500.00, Comment =”some testing comments”});
repository.order.insert(_order);
repository.save();