![](/img/trans.png)
[英]Use Table-Per-Type for all EF context classes with Fluent API
[英]Mapping EF fluent API with many-to-many and Table-Per-Type
我有以下课程:
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;}
}
在流利的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字段的表(地址),并存储了所有典型的地址信息。 还有许多其他表具有一个AddressId字段,该字段指向Addresses表中的地址。 单个地址可以被许多不同的关系重新使用。
现在,一个帐户有许多地址,但也有关于该地址的其他数据。 我要完成的工作是将地址数据存储在“地址”表中,并将其他数据存储在单独的表中。 帐户可以再次共享一个地址,但不能共享其他地址数据。
您不能将此模型建模为多对多关联(具有透明的联结表),因为联结表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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.