Nyr*_*ith 5 c# entity-framework-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; }
}
Run Code Online (Sandbox Code Playgroud)
这给了我:实体类型'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);
}
);
Run Code Online (Sandbox Code Playgroud)
这给了我:导航属性'QuestionId'无法添加到实体类型'ActiveQuestions_Questions',因为实体类型'ActiveQuestions_Questions'上已经存在具有相同名称的属性.
谁能指出我正确的方向?
问题类
public class Question
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string QuestionId {get; set;}
[Required]
public string Text {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Smi*_*mit 12
在EF Core中,KeyAttribute不支持使用定义复合PK ,因此必须使用流畅的API来配置复合PK.
build.HasKey(t => new {t.ActiveQuestionId, t.QuestionId});
Run Code Online (Sandbox Code Playgroud)
您在代码中使用的上述语法是定义复合PK的正确方法.有关更多信息,请参阅文档中的键.
您的代码失败的原因是关系的错误配置.HasOne/ WithOneAPI应该与导航属性(定位其他实体类型的属性)一起使用.在您的配置中,您将在HasOne调用中传递原始属性.由于模型中已经添加了具有相同名称的属性(通过约定和HasKey调用),因此它会抛出异常.即使没有添加它们,也会有不同的例外.以下是有关如何使用流畅API定义关系的文档链接.
| 归档时间: |
|
| 查看次数: |
8529 次 |
| 最近记录: |