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

我有两个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代码中实现呢?


翻阅古今
浏览 463回答 3
3回答

长风秋雁

通过将pocos更改为:public class Order{&nbsp; &nbsp; public int OrderId { get; set; }&nbsp; &nbsp; public virtual Quotation Quotation { get; set; }}public class Quotation{&nbsp; &nbsp; public int QuotationId { get; set; }&nbsp; &nbsp; public virtual Order Order { get; set; }}并使用以下映射文件:public class OrderMap : EntityTypeConfiguration<Order>{&nbsp; &nbsp; public OrderMap()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; this.HasOptional(x => x.Quotation)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .WithOptionalPrincipal()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Map(x => x.MapKey("OrderId"));&nbsp; &nbsp; }}public class QuotationMap : EntityTypeConfiguration<Quotation>{&nbsp; &nbsp; public QuotationMap()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; this.HasOptional(x => x.Order)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .WithOptionalPrincipal()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Map(x => x.MapKey("QuotationId"));&nbsp; &nbsp; }}我们将拥有该数据库(即0..1-0..1)

HUWWW

@Masoud的程序为:modelBuilder.Entity<Order>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .HasOptional(o => o.Quotation)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .WithOptionalPrincipal()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Map(o => o.MapKey("OrderId"));modelBuilder.Entity<Quotation>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .HasOptional(o => o.Order)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .WithOptionalPrincipal()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Map(o => o.MapKey("QuotationId"));通过将代码更改为:modelBuilder.Entity<Order>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .HasOptional(o => o.Quotation)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .WithOptionalPrincipal(o=> o.Order);
打开App,查看更多内容
随时随地看视频慕课网APP