简体   繁体   中英

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?

What is the proper way to map City and MobilePhone classes?

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. In the following example, the HasKey method is used to configure the InstructorID primary key on the OfficeAssignment type.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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