HasOne与OneToMany映射关系

时间:2019-10-09 21:06:23

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

public class Car
{
    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 Name { get; set; }
   public IEnumerable<Country> VisitedCountries { get; set; }
}

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

我将此关系映射为

public class CarConfiguration : IEntityTypeConfiguration<Car>
{
   public void Configure(EntityTypeBuilder<Car> builder)
   {
       builder.ToTable("Car");
       builder.HasKey(x => x.Id);
       builder.Property(x => x.Id).HasColumnName("Id").ValueGeneratedOnAdd();
       builder.HasOne(x => x.Owner);
   }
}

到目前为止,我将OwnerConfiguration文件添加为单独的配置文件

public void Configure(EntityTypeBuilder<Owner> builder)
{
     builder.ToTable("Owner");
     builder.HasMany(x => x.VisitedCountries);
     ...
}
  

我的问题是:我该如何重构它并仅在地图上使用   配置文件(例如CarConfiguration)并删除   OwnerConfiguration文件?

1 个答案:

答案 0 :(得分:0)

对于IEntityTypeConfiguration,它允许将实体类型的配置分解为单独的类,并且不能将其用于其他模型。

通常,有两种方法来配置模型,分别在分开的文件中IEntityTypeConfiguration和在OnModelCreating中直接配置。

在有许多型号的地方,建议对易于配置的单独配置使用IEntityTypeConfiguration。如果只想避免配置modelBuilder.ApplyConfiguration(new CarConfiguration());,则可以尝试像modelBuilder.ApplyEntityTypeConfigurations(Assembly.GetExecutingAssembly());

如果您想在一个地方进行配置,可以像

那样跟随OnModelCreating
    protected override void OnModelCreating(ModelBuilder builder)
    {
            base.OnModelCreating(builder);
            builder.Entity<Car>(c =>
            {
            c.ToTable("Car");
            c.HasKey(x => x.Id);
            c.Property(x => x.Id).HasColumnName("Id").ValueGeneratedOnAdd();
            c.HasOne(x => x.Owner);
            });
    }