首页 > 解决方案 > 如何修复一侧具有两个相同类型实体的一对多关系

问题描述

我正在做一个项目。当我第一次开始时,我有一个订单模型和地址模型。但是,现在我想将 Order 模型更改为具有 AddressTo 和 AddressFrom 而不仅仅是 Address。

地址型号:

public class Address
{
    public int AddressId { get; set; }
    public int ZipCodeId { get; set; }
    public string Street { get; set; }
    public int Nr { get; set; }
    public virtual ICollection<Order> Order { get; set; }
    public virtual ZipCode ZipCode { get; set; }
} 

订购型号:

public class Order
{   
    public int OrderId { get; set; }
    public int CustomerId { get; set; }
    public virtual Address Address { get; set; }
    public DateTime OrderDate { get; set; } 
    public DateTime SentDate { get; set; } 
    public string Title { get; set; }
    public string Type { get; set; }
    public string Content { get; set; }
    public int ExpectedHours { get; set; }
    public int AmountWorkers { get; set; }
    public virtual Customer Customer{ get; set; }
}

我想要的顺序:

public class Order
{   
    public int OrderId { get; set; }
    public int CustomerId { get; set; }
    public virtual Address AddressTo { get; set; }
    public virtual Address AddressFrom { get; set; }
    public DateTime OrderDate { get; set; } 
    public DateTime SentDate { get; set; } 
    public string Title { get; set; }
    public string Type { get; set; }
    public string Content { get; set; }
    public int ExpectedHours { get; set; }
    public int AmountWorkers { get; set; }
    public virtual Customer Customer{ get; set; }
}

我已经意识到没有解决这个问题FluentApi是不可能的。但是,我发现很难克服这个问题。

我想要的是我在数据库中的 Order 表来显示 ID 列AddressToIdAddressFromId,而不仅仅是AddressId(现在就是这样)。

非常感谢社区对此的帮助。

标签: c#entity-framework-coreone-to-manyef-fluent-api

解决方案


首先 public virtual ICollection<Order> Order { get; set; }从模型类中删除导航属性,Address如下所示:

public class Address
{
    public int AddressId { get; set; }
    public int ZipCodeId { get; set; }
    public string Street { get; set; }
    public int Nr { get; set; }

    public virtual ZipCode ZipCode { get; set; }
}

然后将 AddressFromIdAddressToId属性添加到您的Order模型类,如下所示:

public class Order
{
    public int OrderId { get; set; }
    ..............
    public int AddressFromId { get; set; }
    public virtual Address AddressFrom { get; set; }

    public int AddressToId { get; set; }
    public virtual Address AddressTo { get; set; }

    ................
}

然后你的Order配置如下:

public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.HasOne(o => o.AddressFrom).WithMany().HasForeignKey(o => o.AddressFromId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(o => o.AddressTo).WithMany().HasForeignKey(o => o.AddressToId)
            .OnDelete(DeleteBehavior.Restrict);
    }
}

然后在OnModelCreating如下DbContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.ApplyConfiguration(new OrderConfiguration());  
}

推荐阅读