本文介绍了首先通过 Fluent API 在 EF 代码中实现零或一到零或一的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个 POCO 课程:
I have two POCO classes:
订单类:
public class Order
{
public int Id { get; set; }
public int? QuotationId { get; set; }
public virtual Quotation Quotation { get; set; }
....
}
引用类:
public class Quotation
{
public int Id { get; set; }
public virtual Order Order { get; set; }
....
}
- 每个
Order
可以由一个或零个引用构成,并且 - 每个报价可能导致订单.
- Each
Order
may be made from one or zero quotation, and - each quotation may cause an order.
所以我有一个一或零"到一或零"关系,如何在 EF
Code first by Fluent
API 中实现这一点?
So I have an "one or zero" to "one or zero" relation, how can I implement this, in EF
Code first by Fluent
API?
推荐答案
通过将 pocos 更改为:
By changing pocos to:
public class Order
{
public int OrderId { get; set; }
public virtual Quotation Quotation { get; set; }
}
public class Quotation
{
public int QuotationId { get; set; }
public virtual Order Order { get; set; }
}
并使用这些映射文件:
public class OrderMap : EntityTypeConfiguration<Order>
{
public OrderMap()
{
this.HasOptional(x => x.Quotation)
.WithOptionalPrincipal()
.Map(x => x.MapKey("OrderId"));
}
}
public class QuotationMap : EntityTypeConfiguration<Quotation>
{
public QuotationMap()
{
this.HasOptional(x => x.Order)
.WithOptionalPrincipal()
.Map(x => x.MapKey("QuotationId"));
}
}
我们将拥有这个数据库(即 0..1-0..1):
we will have this DB(that means 0..1-0..1):
特别感谢 (Vahid Nasiri 先生)
这篇关于首先通过 Fluent API 在 EF 代码中实现零或一到零或一的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!