EF 模型验证异常 类型中的每个属性名称都必须是唯一的



在实体框架中,我正在尝试根据本教程配置0到许多关系。在这里,学生可以有 0 个或多个联系人。但是代码在运行时显示以下异常。

System.Data.Entity.ModelConfiguration.ModelValidationException

学生 ID:名称:类型中的每个属性名称必须是唯一的。财产名称"学生 ID"已定义。

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);
}

我也尝试删除HasForeignKey。但没有任何效果。

您忘了为学生声明密钥

modelBuilder.Entity<Student>().HasKey(x => x.StudentId);

首先,我认为适当的关系是一对多,一个学生可以有很多联系人(从0到多(。

我以这种方式建立了关系:

public class Student
{
    public Student()
    {
        Contacts = new HashSet<Contacts>();
    }
    public int StudentId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Contact> Contacts { get; set; }
}
public class Contact 
{
    public int ContactId { get; set; }
    public string Name { get; set; }
    public int StudentId { get; set; } //usually I use Annotations here to create the DB like.. [Column("column_name")]
    //Here I use [InverseProperty(Contact), ForeignKey("StudentId")]
    public virtual Student Student { get; set; }
}
public static void Configure(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Contacts>.HasOne(a => a.Student).WithMany(b => b.Contacts).HasForeignKey(a => a.StudentId);    
}

它应该在没有注释的情况下工作。

最新更新