简体   繁体   English

EF Core 2 映射关系

[英]EF Core 2 mapping relationships

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

Do I need to set PK explicitely or it will be set by convention?我需要明确设置 PK 还是按惯例设置?

What is the proper way to map City and MobilePhone classes? map City 和 MobilePhone 类的正确方法是什么?

The Entity Framework convention for primary keys is:主键的实体框架约定是:

Your class defines a property whose name is “ID” or “Id” or a class name followed by “ID” or “Id” To explicitly set a property to be a primary key, you can use the HasKey method.您的 class 定义了一个属性,其名称为“ID”或“Id”或 class 名称后跟“ID”或“Id”。要将属性显式设置为主键,可以使用 HasKey 方法。 In the following example, the HasKey method is used to configure the InstructorID primary key on the OfficeAssignment type.在以下示例中,HasKey 方法用于配置 OfficeAssignment 类型的 InstructorID 主键。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM