问题描述
请参阅上一篇文章:
我已经成功实现了用户阿卜杜拉(abdullah)提出的修改后的解决方案,但是我遇到了以下异常:
I have successfully implemented the modified solution proposed by user Abdullah but I have encountered the exception below:
示例代码如下:
public class School
{
public School()
{
Students = new HashSet<Student>();
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }
[Description("Some Text")]
public string Description { get; set; }
[Description("Some text")]
public ICollection<Student> Students{ get; set; }
}
我从异常消息中了解到,没有为学生生成任何列.检查数据库,显示Student表的列SchoolId为FK.
I understand from the exception message, there is no column generated for Students. Checking the DB shows that the Student table have the column SchoolId as FK.
所以这里的问题是:当EF在另一个表中生成FK列时,如何添加/更新FK描述?
So the question here is: how do I go about adding/updating the FK description when EF generates the FK column in another table?
推荐答案
尽管他没有回答我的问题,但我要感谢 Raihan使我有了再次检查如何声明外键的想法.:)
Although he did not answer my question, I have to thank Raihan for giving me the idea to check again on how Foreign Keys can be declared. :)
基于实体框架教程,可以通过3种方式声明外键:
Based on Entity Framework Tutorial, a foreign key can be declared 3 ways:
- 从属实体中的外键标量属性上的[ForeignKey(NavigationPropertyName)].
- 从属实体中相关参考导航属性上的[ForeignKey(ForeignKeyPropertyName)].
- 主体实体中导航属性上的[ForeignKey(ForeignKeyPropertyName)].
还引用在Entity Framework Tutorial网站上如何声明一对多关系部分,我们可以看到我在问题中描述的方法是公约2.
Also referencing to how a one-many relationship can be declared section in Entity Framework Tutorial website, we can see that the method which I had described in my question is Convention 2.
为了使Raihan用户的建议生效,我将需要将多个声明更改为Convention 3,这是在 School
和 Student
类.如下所示:
In order for User Raihan's suggestion to work, I will need to change the one-many declaration to Convention 3, which is to declare a navigational properties at both the School
and Student
classes. Like below:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public School School { get; set; }
}
public class School
{
public int GradeID { get; set; }
public string GradeName { get; set; }
public string Section { get; set; }
public ICollection<Student> Student { get; set; }
}
请参考同一网站中的外键声明示例,如下所示,需要对 Student
类进行进一步修改,以使(Description)属性起作用:
Referencing the foreign key declaration sample in the same website, the Student
class needs to be further modified as shown below in order for the (Description) attribute to work:
public class Student
{
[Description("Id of Student")]
[Key]
public int Id { get; set; }
[Description("Name of Student")]
public string Name { get; set; }
[Description("Some Description")]
public int SchoolId {get; set;}
public School School { get; set; }
}
我仍在寻找一种获取列说明的较短方法,因此,如果您认为您的解决方案比我的解决方案更优雅,请回复.:)
I am still looking for a shorter way to get the column description in so please do reply if you think your solution is more elegant than mine.. :)
这篇关于如何使用EF 6在另一个表中添加外键的列描述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!