0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.