EF ModelValidationException Each property name in a type must be unique

c# ef-fluent-api entity-framework entity-framework-6

Question

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.

1
0
4/18/2018 3:38:14 PM

Popular Answer

You forgot to declare the key for Student

modelBuilder.Entity<Student>().HasKey(x => x.StudentId);
1
4/18/2018 2:09:15 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow