问题
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