C# 重复外键
我有两个POCO实体,ApplicationUser和AccountC# 重复外键,c#,entity-framework,C#,Entity Framework,我有两个POCO实体,ApplicationUser和Account 一个帐户有多个应用程序用户 每个帐户都有一个应用程序用户,他是计费联系人 因此,我的实体是: public class ApplicationUser { public string Id { get; set; } public int AccountId { get; set; } public virtual Account Account { get; set; } } public c
- 一个帐户有多个应用程序用户
- 每个帐户都有一个应用程序用户,他是计费联系人
public class ApplicationUser
{
public string Id { get; set; }
public int AccountId { get; set; }
public virtual Account Account { get; set; }
}
public class Account
{
public int Id { get; set; }
[ForeignKey("BillingContact")]
public string BillingContactId { get; set; }
public virtual ApplicationUser BillingContact { get; set; }
public virtual ICollection<ApplicationUser> Users { get; set; }
公共类应用程序用户
{
公共字符串Id{get;set;}
public int AccountId{get;set;}
公共虚拟帐户{get;set;}
}
公共类帐户
{
公共int Id{get;set;}
[外键(“BillingContact”)]
公共字符串BillingContactId{get;set;}
公共虚拟应用程序用户计费联系人{get;set;}
公共虚拟ICollection用户{get;set;}
我的问题是,当我创建迁移时,代码首先只部分理解BillingContact是一个外键。迁移代码使用BillingContactId外键创建Account表,但它也创建了一个额外的Account_Id外键字段
我找到了一个解决方法,但它严重地没有通过“嗅觉”测试。根本的问题是,我在这两个类之间有多个关系,这首先会混淆代码。特别是,ApplicationUser实体没有作为BillingContact外键“另一端”的导航属性
如果我向ApplicationUser添加导航属性,并用InverseProperty属性标记它,那么代码首先似乎理解外键,而不会创建额外字段:
public class ApplicationUser
{
public string Id { get; set; }
public int AccountId { get; set; }
public virtual Account Account { get; set; }
[InverseProperty("BillingContact")]
public virtual ICollection<Account> MyBillingAccounts { get; set; }
}
公共类应用程序用户
{
公共字符串Id{get;set;}
public int AccountId{get;set;}
公共虚拟帐户{get;set;}
[反向属性(“BillingContact”)]
公共虚拟ICollection MyBillingAccounts{get;set;}
}
此解决方法的问题是MyBillingAccounts导航属性完全是假的。帐户具有相关的ApplicationUser,即计费联系人,但反向关系(从ApplicationUser导航回BillingContactId外键)没有实际意义
那么……有没有更好(或正确)的方法来先教授代码有关BillingContactId外键的知识?您只能通过流畅的映射来实现这一点。例如,在覆盖上下文的
OnModelCreating
时:
modelBuilder.Entity<Account>()
.HasOptional(acc => acc.BillingContact)
.WithMany()
.HasForeignKey(acc => acc.BillingContactId);
modelBuilder.Entity()
.HAS可选(acc=>acc.BillingContact)
.有很多
.HasForeignKey(acc=>acc.BillingContactId);
空的
WithMany()
调用表示关联的反向端没有导航属性。感谢您的即时回答!实际上,我想我需要HasRequired()
而不是HasOptional()
,因为我希望FK是必需的(不可为null).但这个细节在行动中并不清楚。