Entity Framework - Many to many with shared foreign key

三世轮回 提交于 2019-12-12 03:43:13

问题


I would like my Business and Customer tables to both reference the same Address table, so I created a many to many relationship table "EntityAddress"

My EntityAddress table has a EntityID field that I want the Business and Customer tables to share. However when I run my code below, my EntityAddress table has BusinessId and CustomerId fields that are auto-created.

Any idea why this is happening? Thanks!!

builder.Entity<EntityAddress>().HasKey(x => new { x.EntityId, x.AddressId });
builder.Entity<EntityAddress>().HasOne(pc => pc.Address).WithMany(c => c.EntityAddresses).HasForeignKey(pc => pc.AddressId);
builder.Entity<EntityAddress>().HasOne(pc => pc.Business).WithMany(p => p.EntityAddresses).HasForeignKey(pc => pc.EntityId);
builder.Entity<EntityAddress>().HasOne(pc => pc.Customer).WithMany(p => p.EntityAddresses).HasForeignKey(pc => pc.EntityId);


public class Business
{
    [Key] public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<EntityAddress> EntityAddresses { get; set; }
}

public class Customer
{
    [Key] public int Id { get; set; }
    public string Name{ get; set; }
    public virtual ICollection<EntityAddress> EntityAddresses { get; set; }
}

public class EntityAddress
{
    [Key] public int Id { get; set; }
    public int EntityId { get; set; }
    public Enums.EntityType EntityType { get; set; }
    public int AddressId { get; set; }
    public virtual Address Address { get; set; }
    public virtual Business Business { get; set; }
    public virtual Customer Customer { get; set; }
}

public class Address
{
    [Key] public int Id { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
    public virtual ICollection<EntityAddress> EntityAddresses { get; set; }
}

来源:https://stackoverflow.com/questions/40497057/entity-framework-many-to-many-with-shared-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!