![](/img/trans.png)
[英]ASP .NET Core MVC, Entity Framework, Identity - composite key consisting of foreign keys
[英]Creating composite primary key consisting off foreign keys in fluent API with ASP.NET core
這里的問題是如何生成由兩個外鍵組成的復合主鍵?
我試過了:
public class ActiveQuestions_Questions
{
[Column(Order = 0), Key, ForeignKey("ActiveQuestion")]
public string ActiveQuestionId {get; set;}
[Column(Order = 1), Key, ForeignKey("Question")]
public string QuestionId {get; set; }
}
這給了我:實體類型'ActiveQuestions_Questions'具有使用數據注釋定義的復合主鍵。 要設置復合主鍵,請使用fluent API。
然后我嘗試在沒有注釋的模型構建器中使用流暢的api。
builder.Entity<ActiveQuestions_Questions>(
build =>
{
build.HasKey(t => new {t.ActiveQuestionId, t.QuestionId});
build.HasOne(t => t.QuestionId).WithOne().HasForeignKey<Question>(qe => qe.QuestionId);
build.HasOne(t => t.ActiveQuestionId).WithOne().HasForeignKey<ActiveQuestion>(qe => qe.ActivateQuestionId);
}
);
這給了我:導航屬性'QuestionId'無法添加到實體類型'ActiveQuestions_Questions',因為實體類型'ActiveQuestions_Questions'上已經存在具有相同名稱的屬性。
誰能指出我正確的方向?
問題類
public class Question
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string QuestionId {get; set;}
[Required]
public string Text {get; set;}
}
ActiveQuestion類:
public class ActiveQuestion
{
private DateTime _lastUpdated = DateTime.Now;
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string ActivateQuestionId {get; set;}
public DateTime LastUpdated
{
get
{
return this._lastUpdated;
}
set
{
this._lastUpdated = value;
}
}
}
在EF Core中,不支持使用KeyAttribute
定義復合PK,因此必須使用流暢的API來配置復合PK。
build.HasKey(t => new {t.ActiveQuestionId, t.QuestionId});
您在代碼中使用的上述語法是定義復合PK的正確方法。 有關更多信息,請參閱文檔中的鍵 。
您的代碼失敗的原因是關系的錯誤配置。 HasOne
/ WithOne
API應該與導航屬性(定位其他實體類型的屬性)一起使用。 在您的配置中,您將在HasOne
調用中傳遞原始屬性。 由於模型中已經添加了具有相同名稱的屬性(通過約定和HasKey
調用),因此它會拋出異常。 即使沒有添加它們,也會有不同的例外。 以下是有關如何使用流暢API定義關系的文檔鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.