[英]Creating model from existing table in Entity Framework
I have many-to-many relation Student-Course which I realised using virtual collection list and I got the next generated migration code : 我有多对多的学生课程,通过使用虚拟馆藏清单我意识到了这一点,并得到了下一个生成的迁移代码:
CreateTable(
"dbo.PersonCourses",
c => new
{
Person_Id = c.Int(nullable: false),
Course_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Person_Id, t.Course_Id })
.ForeignKey("dbo.People", t => t.Person_Id, cascadeDelete: true)
.ForeignKey("dbo.Courses", t => t.Course_Id, cascadeDelete: true)
.Index(t => t.Person_Id)
.Index(t => t.Course_Id);
Now I want to map table PersonCourses to some C# class and I wrote 现在我想将表PersonCourses映射到一些C#类,并且我写了
[Table("PersonCourses")]
public class PersonCourses
{
[ForeignKey("Person")]
[Required]
public int PersonId { get; set; }
[ForeignKey("Course")]
[Required]
public int CourseId { get; set; }
}
but it fails with : "PersonCourses" has no key defined.Define the key for this EntityType. 但失败,显示:“ PersonCourses”未定义密钥。为此EntityType定义密钥。
You should add attribute [Key] property PersonCoursesId: 您应该添加属性[Key]属性PersonCoursesId:
public partial class Category
{
[Key]
public int PersonCoursesId { get; set; }
[ForeignKey("Person")]
public int PersonId { get; set; }
[ForeignKey("Course")]
public int CourseId { get; set; }
}
The problem is that EF can work only when it knows primary key of table. 问题是EF仅在知道表的主键时才能工作。 By default EF recognize as primary key property with name Id.
默认情况下,EF识别为名称为ID的主键属性。 If your table has another primary key, you can mark it with attribute [Key] or set Key with fluent configuration.
如果您的表有另一个主键,则可以用属性[Key]对其进行标记,或者使用流畅的配置来设置Key。
Hope this helps. 希望这可以帮助。
You need the [Key] attribute above properties that make up the primary key. 您需要在组成主键的属性上方的[Key]属性。 For composite primary keys you also need to specify a column order.
对于复合主键,您还需要指定列顺序。 See https://msdn.microsoft.com/en-us/data/jj591583.aspx#Composite
请参阅https://msdn.microsoft.com/zh-cn/data/jj591583.aspx#Composite
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.