EF Core 2映射关系

时间:2019-10-22 15:46:57

标签: c# .net entity-framework asp.net-core

public class MobilePhone{
    public int Id {get; set;}
    public string Name { get; set; }
    public Owner Owner { get; set; }
}

public class Owner{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ICollection<City> Cities { get;  set; }
}

public class City
{
    public int Id {get; set;}
    public string Name { get;  set; }        
    public Owner Owner { get;  set; }
}


public class OwnerConfiguration : IEntityTypeConfiguration<Owner>
{
    public void Configure(EntityTypeBuilder<Owner> builder)
    {
        builder.ToTable("Owner");
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Id).HasColumnName("Id").ValueGeneratedOnAdd();
        builder.Property(x => x.FirstName);
        builder.Property(x => x.LastName);
        builder.HasMany(x => x.Cities);
    }
}
  

我需要显式设置PK还是按惯例设置?

     

映射City和MobilePhone类的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

主键的实体框架约定为:

您的类定义了一个名称为“ ID”或“ Id”的属性 或类名后跟“ ID”或“ Id” 要将属性显式设置为主键,可以使用HasKey方法。在下面的示例中,HasKey方法用于在OfficeAssignment类型上配置InstructorID主键。

    modelBuilder.Entity<OfficeAssignment>().HasKey(t => t.InstructorID);