我只是 EF 代码优先模型的初学者。给定两个映射到当前遗留 MS SQL 数据库的 POCO 类。它们与建立一对多关系的复合外键相关联。由于它实际上是一对一的关系,我希望在我的 POCO 对象中有相应的导航属性,并在流式 API 中进行映射。这是我的例子:
public partial class Answer
{
//primary key
public int id { get; set; }
//foreign keys
public int question { get; set; }
public int assignedForm { get; set; }
//simple fields
public short state { get; set; }
public int author { get; set; }
//navigation property
public virtual AssignedQuestion AssignedQuestion { get; set; }
}
public partial class AssignedQuestion
{
// primary keys
public int id { get; set; }
public int assignedForm { get; set; }
//simple field
public string content { get; set; }
//navigation property
//public virtual ICollection<Answer> Answers { get; set; }
public virtual Answer Answer { get; set; }
}
如果我想做一对多的关系,我只需取消注释“Answers”集合并拥有 Fluent API 映射:
modelBuilder.Entity<AssignedQuestion>()
.HasKey(q => new { q.id, q.assignedForm });
modelBuilder.Entity<Answer>()
.HasRequired(a => a.AssignedQuestion)
.WithMany(aq=>aq.Answers)
.HasForeignKey(a => new { a.question,a.assignedForm});
我的目标是使用一对一的关系,并在 AssignedQuestion 中使用“Answer”属性和这样的 Fluent API:
modelBuilder.Entity<AssignedQuestion>()
.HasKey(q => new { q.id, q.assignedForm });
modelBuilder.Entity<Answer>()
.HasRequired(a => a.AssignedQuestion)
.WithOptional(aq => aq.Answer);
//.HasForeignKey(a => new { a.question, a.assignedForm });
问题是我无法准确指定外键字段(如前面的示例)并取消注释 HasForeignKey 调用。在这种情况下,EF 尝试使用常规字段名称“AssignedQuestion_ID”和“AssignedQuestion_AssignedForm”而不是 Answer 表中的“question”和“assignedForm”来连接表。除了更改字段名称之外,Fluent API 中是否有其他解决方法?