我有以下课程:
public class Account
{
public int Id {get; set;}
public ICollection<AccountAddress> Addresses {get; set;}
}
public class Address
{
public int Id {get; set;}
public string Street1 {get; set;}
... //Other address properties
}
public class AccountAddress : Address
{
public int AccountId {get; set;}
public DateTime BeginDate {get; set;}
public DateTime PurgeDate {get; set;}
public bool IsPrimary {get; set;}
}在我的fluent api配置中,我有以下内容:
public AccountConfiguration()
{
ToTable("accounts");
HasKey(m => m.Id);
Property(m => m.Id).HasColumnName("accountid");
...
//This is wrong because it does not allow many to many
HasMany(m => m.Addresses).WithRequired().HasForeignKey(m => m.AccountId);
}
public AddressConfiguration()
{
ToTable("addresses");
HasKey(a => a.Id);
Property(a => a.Id).HasColumnName("addressid");
...
}
public AccountAddressConfiguration()
{
ToTable("acctaddrs");
HasKey(m => new {m.Id, m.AccountId});
...
}我试图编辑我的AccountConfiguration上的关系,使之成为一种多对多的关系,但我很难找到如何定义这种关系。
这背后的想法是,帐户可以有多个地址,有些帐户可以绑定到同一个地址。
谢谢你的帮助!
编辑,所以这里是我需要完成的。我有一个表(地址),它有一个Id字段,并存储所有典型的地址信息。还有许多其他表具有指向address表中某个地址的AddressId字段。一个地址可能会被许多不同的关系重复使用。
现在,一个帐户有许多地址,但也有关于一个地址的附加数据。我想要完成的是将地址数据存储在address表中,并将附加数据存储在单独的表中。同样,帐户可以共享地址,但不能共享附加地址数据。
发布于 2013-02-04 21:57:12
您不能将其建模为多到多的asociation (使用透明的连接表),因为连接表、AccountAddress包含的不仅仅是主键值。
作为真正的连接表,AccountAddress还应该包含AddressId
public class AccountAddress : Address
{
[ForeignKey("Account"]] // Or fluent mapping
public int AccountId {get; set;}
public virtual Account Account {get; set;}
[ForeignKey("Address"]] // Or fluent mapping
public int AddressId {get; set;}
public virtual Address Address {get; set;}
public DateTime BeginDate {get; set;}
public DateTime PurgeDate {get; set;}
public bool IsPrimary {get; set;}
}而且您的帐户和地址类都应该有一个ICollection<AccountAddress>。
您可以将其映射为Address 1 - n AccountAddress n - 1 Account。
要获得例如一个帐户的地址,请:
Accounts.Select(a => a.AccountAddresses
// .Where(a => a.IsPrimary // for instance
.Select(aa => aa.Address))https://stackoverflow.com/questions/14690911
复制相似问题