简体   繁体   中英

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

[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.

You should add attribute [Key] property 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. By default EF recognize as primary key property with name Id. If your table has another primary key, you can mark it with attribute [Key] or set Key with fluent configuration.

Hope this helps.

You need the [Key] attribute above properties that make up the primary key. For composite primary keys you also need to specify a column order. See https://msdn.microsoft.com/en-us/data/jj591583.aspx#Composite

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM