【发布时间】:2012-05-13 16:22:19
【问题描述】:
我有三个班级:
public partial class Student : Contact
{
//Inherited from Contact:
//public int ContactId { get; set; }
//public string FirstName { get; set; }
//public string LastName { get; set; }
public virtual StudentExam StudentExam { get; set; }
}
public partial class Exam
{
public int ExamId { get; set; }
public string Title { get; set; }
public DateTime Date { get; set; }
public virtual StudentExam StudentExam { get; set; }
}
public partial class StudentExam
{
public byte Score { get; set; }
public int ContactId { get; set; }
public int ExamId { get; set; }
public virtual Student Student { get; set; }
public virtual Exam Exam { get; set; }
}
当尝试初始化 DbContext 时,它会抛出 ModelValidationException:
在模型生成过程中检测到一个或多个验证错误:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'StudentExam' 没有定义键。定义此 EntityType 的键。
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'StudentExams' 基于没有定义键的类型'StudentExam'。
我尝试将StudentExam 类的属性更改为以下内容:
[Key, ForeignKey("Student"), Column(Order = 0)]
public int ContactId { get; set; }
[Key, ForeignKey("Exam"), Column(Order = 1)]
public int ExamId { get; set; }
现在我得到了这个异常:
\tSystem.Data.Entity.Edm.EdmAssociationEnd: : 多重性在关系“StudentExam_Student”中的角色“StudentExam_Student_Source”中无效。因为从属角色属性不是关键属性,所以从属角色的多重性的上限必须是“*”。 \tSystem.Data.Entity.Edm.EdmAssociationEnd: : 多重性在关系“StudentExam_Exam”中的角色“StudentExam_Exam_Source”中无效。因为从属角色属性不是关键属性,所以从属角色的多重性的上限必须是'*'。
有什么方法可以通过数据注释实现这一点(当我可以使用数据注释时,我不喜欢使用流畅的 API;流畅的 API 会导致代码混乱。
【问题讨论】:
标签: entity-framework entity-framework-4.1 ef-code-first code-first entity-relationship