为了账号安全,请及时绑定邮箱和手机立即绑定

首先通过Fluent API在EF代码中实现零或一对零或一个关系

首先通过Fluent API在EF代码中实现零或一对零或一个关系

C#
翻阅古今 2019-11-28 14:19:38
我有两个POCO课程public class Order{    int id;    string code;    int? quotationId;  //it is foreign key    public int Id{get;set;}    public string Code{get;set;}    public int? QuotationId{get;set;}    Quotation quotation;    public virtual Quotation Quotation { get; set; }    ....}public class Quotation{    int Id;    string Code;    public int Id{get;set;}    public string Code{get;set;}    Order order;    public virtual Order Order { get; set; }    ....   }每个订单可能由一个或零个报价组成,并且每个报价都可能导致一个订单,所以我有一个“一或零”到“一或零”的关系,我该如何首先通过fluent API在EF代码中实现呢?
查看完整描述

3 回答

?
长风秋雁

TA贡献1757条经验 获得超7个赞

通过将pocos更改为:


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)


查看完整回答
反对 回复 2019-11-28
?
HUWWW

TA贡献1874条经验 获得超12个赞

@Masoud的程序为:


modelBuilder.Entity<Order>()

            .HasOptional(o => o.Quotation)

            .WithOptionalPrincipal()

            .Map(o => o.MapKey("OrderId"));


modelBuilder.Entity<Quotation>()

            .HasOptional(o => o.Order)

            .WithOptionalPrincipal()

            .Map(o => o.MapKey("QuotationId"));


通过将代码更改为:


modelBuilder.Entity<Order>()

            .HasOptional(o => o.Quotation)

            .WithOptionalPrincipal(o=> o.Order);


查看完整回答
反对 回复 2019-11-28
  • 3 回答
  • 0 关注
  • 462 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信