In entity framework I am trying to configure a 0 to Many relationships based on this tutorial. Here Student can have 0 or many contacts. But the code shows below exception in runtime.
System.Data.Entity.ModelConfiguration.ModelValidationException
StudentId: Name: Each property name in a type must be unique. Property name 'StudentId' is already defined.
public class Student
{
public Student()
{
Contacts = new EntityHashSet<Contact>();
}
public int StudentId { get; set; }
public string Name { get; set; }
public virtual IEntityHashSet<Contact> Contacts { get; private set; }
}
public class Contact
{
public int ContactId { get; private set; }
public string Name { get; private set; }
public int StudentId { get; set; }
public virtual Student Student { get; protected set; }
}
public static void Configure(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasMany(e => e.Contacts)
.WithRequired(e => e.Student)
.HasForeignKey(e => e.StudentId);
}
I have tried removing HasForeignKey also. But nothing works.
You forgot to declare the key for Student
modelBuilder.Entity<Student>().HasKey(x => x.StudentId);