'Connecting multiple tables using Entity Framework (code first)
I've created 2 table for my database, and connect them using foreign key, example:
internal class Student
{
[Key]
public int StudentId { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string FirstName { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string LastName { get; set; }
[ForeignKey("GroupId")]
public int GroupId { get; set; }
public virtual Group Group { get; set; }
}
internal class Group
{
[Key]
public int GroupId { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
It works just fine, but then I had to join a third table (which is connected via foreign key with Group table). So I've changed my group table a bit, and created another table called Course
internal class Group
{
[Key]
public int GroupId { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; }
//foreign key
[ForeignKey("Course")]
public int CourseId { get; set; }
public virtual Course Course { get; set; }
}
internal class Course
{
[Key]
public int CourseId { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string Name { get; set; }
[Column(TypeName = "nvarchar(250)")]
public string Description { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}
It doesn't work as I expected, cause when I'm trying to create a migration I'm getting this error message "The property 'GroupId' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type."
Solution 1:[1]
As the documentation indicates that, in your case, ForeignKey takes the field name of your "Group" dependent entity; https://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx
So you must change "GroupId" to "Group" in this line;
[ForeignKey("GroupId")]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ahmet Remzi EKMEKCI |
