【发布时间】:2014-01-16 03:45:48
【问题描述】:
我正在使用 EF 6 和 Code First 开发与保险行业相关的应用程序。对于这个应用程序,每个账户可以有多个策略,每个策略可以有多个事务。此外,每个帐户都必须与身份(姓名、地址、城市等)有关系。 Policy 也与 Identity 有关系,但它是可选的。
由于 Account -> Identity and Account ->> Policy -> Identity,我发现我需要使用 Fluent API 将其中至少一条路径的 WillCascadeDelete 设置为 False。
我的问题是如何将 Account.IdentityId 和 Policy.InsuredIdentityId 属性配置为外键?我已经避免将任何导航/外键字段添加到身份类,因为永远不应该有从一个身份导航到另一个类的理由。这就是我很难弄清楚这一点的原因吗?
public class Account
{
public long Id { get; set; }
public long IdentityId { get; set; }
public virtual Identity Identity { get; set; }
public ICollection<Policy> Policies { get; set; }
}
public class Policy
{
public long Id { get; set; }
public long AccountId { get; set; }
public virtual Account Account { get; set; }
public bool UseAccountIdentity { get; set; }
public long InsuredIdentityId { get; set; }
public virtual Identity InsuredIdentity { get; set; }
}
public class Identity
{
public long Id { get; set; }
public string Name { 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 class AccountConfiguration : EntityTypeConfiguration<Account>
{
public AccountConfiguration()
{
HasRequired(a => a.Identity).WithOptional(x => x.Account).WillCascadeOnDelete(false);
HasMany(a => a.Policies).WithRequired(p => p.Account).HasForeignKey(p => p.AccountId);
}
}
public class PolicyConfiguration : EntityTypeConfiguration<Policy>
{
public PolicyConfiguration()
{
HasOptional(p => p.InsuredIdentity).WithOptionalPrincipal().WillCascadeOnDelete(false);
}
}
作为一个附带问题,EF Code First 是否有任何好的书籍或其他参考资料?我有 Julia Lerman 的 Programming Entity Framework: Code First,这对于它所涵盖的示例来说很好,但它没有涵盖足够的案例。
【问题讨论】:
标签: c# entity-framework ef-code-first