Reputation: 273
I have an EF Code First test app. I want to make one-to-many associations between 3 tables. I want to make a schema which looks like this http://gyazo.com/7a1800230a3838adecaafc5cb6676b25.png. When i launch my app VS says me:
The ForeignKeyAttribute on property 'EducationLevels' on type 'ConsoleApplication2.Employee' is not valid. The foreign key name 'EducationLevelId' was not found on the dependent type 'ConsoleApplication2.EducationLevel'. The Name value should be a comma separated list of foreign key property names.
Here it is my code:
class Program
{
static void Main(string[] args)
{
using (EmployeesContext context = new EmployeesContext())
{
Profession p = new Profession { Id = 0, NameOfProfession = "myprof" };
context.Profession.Add(p);
context.SaveChanges();
}
}
}
public enum Sex { Man = 0, Woman = 1 }
public class Employee
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public byte Age { get; set; }
public Sex Sex { get; set; }
public int EducationLevelId { get; set; }
public int ProfessionId { get; set; }
[ForeignKey("EducationLevelId")]
public virtual ICollection<EducationLevel> EducationLevels { get; set; }
[ForeignKey("ProfessionId")]
public virtual ICollection<Profession> Professions { get; set; }
}
public class EducationLevel
{
[Key]
public int Id { get; set; }
public string Level { get; set; }
public virtual Employee Employees { get; set; }
}
public class Profession
{
[Key]
public int Id { get; set; }
public string NameOfProfession { get; set; }
public virtual Employee Employees { get; set; }
}
public class EmployeesContext : DbContext
{
public DbSet<Employee> Employee { get; set; }
public DbSet<EducationLevel> EducationLevel { get; set; }
public DbSet<Profession> Profession { get; set; }
}
Upvotes: 0
Views: 232
Reputation: 177133
You need to swap collection and reference navigation properties (an Employee
has one EducationLevel
and one Profession
, not many, and an EducationLevel
has many Employees
and not one, and a Profession
has many Employees
and not one):
public class Employee
{
// ...
public int EducationLevelId { get; set; }
public int ProfessionId { get; set; }
[ForeignKey("EducationLevelId")]
public virtual EducationLevel EducationLevel { get; set; }
[ForeignKey("ProfessionId")]
public virtual Profession Profession { get; set; }
}
public class EducationLevel
{
// ...
public virtual ICollection<Employee> Employees { get; set; }
}
public class Profession
{
// ...
public virtual ICollection<Employee> Employees { get; set; }
}
Upvotes: 1