复合主键与两个不同的表中的两个外键mvc
问题描述:
我是相当新的ASP.NET MVC,我试图找到一个解决方案,但我无法找到一个类似的例子,我读过这是因为当它必须是*时,我的关系是空的。我希望我的ProposalFB表具有来自不同表格(讲师和学生)的讲师电子邮件(leeEmail)和学生电子邮件(studEmail)的组合主键,起初,我认为如果有数据讲师和学生表不幸的是没有工作。每当我尝试脚手架,我得到 复合主键与两个不同的表中的两个外键mvc
我的模式是这样的: Student.cs
public class Student
{
[Key]
public string studEmail { get; set; }
public string projectType { get; set; }
public string projectTitle { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> year { get; set; }
public virtual ProposalFB ProposalFB { get; set; }
}
Lecturer.cs
public class Lecturer
{
[Key]
public string lecEmail { get; set; }
public virtual ProposalFB ProposalFB { get; set; }
}
ProposalFB.cs
public class ProposalFB
{
[Key, ForeignKey("Student"), Column(Order = 0)]
public string studEmail { get; set; }
[Key, ForeignKey("Lecturer"), Column(Order = 1)]
public string lecEmail { get; set; }
public string feedback1 { get; set; }
public string feedback2 { get; set; }
public string feedback3 { get; set; }
public string feedback4 { get; set; }
public string feedback5 { get; set; }
public float proposalMark { get; set; }
public Nullable<System.DateTime> createdOn { get; set; }
public Nullable<System.DateTime> modified { get; set; }
public bool status { get; set; }
public virtual Student Student { get; set; }
public virtual Lecturer Lecturer { get; set; }
}
真正感谢一些指导如何纠正
答
您的ProposalFB
实体代表Student
和Lecturer
之间的关系many-to-many
。因此Student
和Lecturer
不能有一个单一的项目ProposalFB
属性,它应该是ProposalFB
集合:
public class Student
{
// ...
public virtual ICollection<ProposalFB> ProposalFB { get; set; }
}
public class Lecturer
{
// ...
public virtual ICollection<ProposalFB> ProposalFB { get; set; }
}
+0
这按预期工作,并纠正了我所遇到的问题 – Newbie
1.组合键通常是一个坏主意。 2.由外键组成的复合键总是*一个坏主意。 3.键(主键或外键)应该放在索引列上,这些键不太适合。长与短:只需在桌面上添加一些好的身份主键,并停止所有这些愚蠢行为。 –
@ChrisPratt我这样做的理由是为了跟踪学生和讲师的电子邮件地址在“ProposalFB”表中不再重复,是否有一种比我提出的模型更容易管理的方法? – Newbie
当然。只需在列上添加一个唯一的约束。不需要成为关键。 –