我有一个组织类和一个用户类,如下所示,并且我希望能够为每个单独分配一个地址 - 不需要两个单独的多对多表用于 AddressUser 和 AddressOrganization、AddressAnything 等。原因是我可能有多个实体,我想为其分配一个地址,并且不希望每个需要地址记录的单个实体都有一个中间连接表。
我也不想为需要与其关联的地址的每个实体存储像 Address.OrganizationId 或 Address.UserId 这样的外键。
有没有办法 Fluent API 或 Code-First Data Annotations 可以容纳某种具有对象类型的复合通用外键?
像 DomainObjectType 表?
域对象类型:
public class DomainObjectType
{
[Key]
public int Id { get; set; } // seeded
public string ObjectType { get; set; } // User or Organization
}
DomainObjectType 将被播种:
var objTypes = new List<DomainObjectType>
{
new DomainObjectType() { Id = 1, ObjectType = "User" },
new DomainObjectType() { Id = 2, ObjectType = "Organization" }
};
objTypes.ForEach(c => context.DomainObjectTypes.Add(c));
context.SaveChanges();
组织:
public class Organization
{
// Primary key
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
#region Navigation Properties
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
#endregion
}
用户
public class User
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int OrganizationId { get; set; }
[ForeignKey("OrganizationId")]
public virtual Organization Organization { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
地址
public class Address
{
// Primary Key
public int Id { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string AddressType { get; set; }
#region Foreign Keys
// not completely sure about this? (maybe move to many-to-many "join" table)
public int DomainObjectId { get; set; } // Composite key; would be either an OrganizationId or UserId
public string DomainObjectTypeId { get; set; } // Composite key
#endregion
#region Navigation Properties
public virtual ICollection<Organization> Organizations { get; set; }
public virtual ICollection<User> Users { get; set; }
#endregion
}
流利的 API 东西:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Configure Code First to ignore PluralizingTableName convention
// If you keep this convention then the generated tables will have pluralized names.
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// one-to-many Organization-to-Users
modelBuilder.Entity<User>()
.HasRequired(u => u.Organization)
.WithMany(o => o.Users)
.HasForeignKey(u => u.OrganizationId);
// what goes here for generic AddressDomainObjectType?
}