gpt4 book ai didi

c# - Entity Framework 一对多,每个层次结构一个表,为每个子类创建一个外键列

转载 作者:可可西里 更新时间:2023-11-01 09:11:51 26 4
gpt4 key购买 nike

我有一个 Garage,其中包含 CarsMotorcycles。汽车和摩托车是 Vehicles。他们在这里:

public class Garage
{
public int Id { get; set; }
public virtual List<Car> Cars { get; set; }
public virtual List<Motorcycle> Motorcycles { get; set; }

public Garage()
{
Cars = new List<Car>();
Motorcycles = new List<Motorcycle>();
}
}

public abstract class Vehicle
{
public int Id { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}

public class Car : Vehicle
{
public int GarageId { get; set; }
public virtual Garage Garage { get; set; }
// some more properties here...
}

public class Motorcycle : Vehicle
{
public int GarageId { get; set; }
public virtual Garage Garage { get; set; }
// some more properties here...
}

为什么 Car 和 Motorcycle 都有 GarageId 和 Garage 属性?如果我将这些属性推送到 Vehicle 父类(super class),EF 会提示并告诉我导航属性必须驻留在具体类中。

继续,这是我的 DbContext:

public class DataContext : DbContext
{
public DbSet<Garage> Garages { get; set; }
public DbSet<Vehicle> Vehicles { get; set; }
public DbSet<Car> Cars { get; set; }
public DbSet<Motorcycle> Motorcycles { get; set; }

public DataContext()
: base("GarageExample")
{

}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}
}

这是一个玩我的玩具的小程序:

class Program
{
static void Main(string[] args)
{
Database.SetInitializer<DataContext>(new DropCreateDatabaseAlways<DataContext>());

using (var db = new DataContext())
{
var car1 = new Car { Make = "Subaru", Model = "Legacy" };
var car2 = new Car { Make = "Porche", Model = "911" };

var bike1 = new Motorcycle { Make = "Suzuki", Model = "GS500" };
var bike2 = new Motorcycle { Make = "Kawasaki", Model = "Ninja" };

var garage = new Garage();

garage.Cars.Add(car1);
garage.Cars.Add(car2);
garage.Motorcycles.Add(bike1);
garage.Motorcycles.Add(bike2);

db.Garages.Add(garage);

db.SaveChanges();
}
}
}

程序运行,并生成以下Vehicles 表:

Id Make     Model  GarageId GarageId1 Discriminator
1 Subaru Legacy 1 null Car
2 Porche 911 1 null Car
3 Suzuki GS500 null 1 Motorcycle
4 Kawasaki Ninja null 1 Motorcycle

由于 Car 和 Motorcycle 都有自己的 GarageId 和 Garage 属性,似乎每个子类都在创建自己的车库外键。我如何告诉 EF(如果可能,通过 Fluent API)Car.Garage 和 Motorcycle.Garage 是同一个东西,并且应该使用相同的列?

这当然是我想要的Vehicles表:

Id Make     Model  GarageId Discriminator
1 Subaru Legacy 1 Car
2 Porche 911 1 Car
3 Suzuki GS500 1 Motorcycle
4 Kawasaki Ninja 1 Motorcycle

最佳答案

在汽车和摩托车类的 GarageId 属性上使用属性 [Column("GarageId")]。

关于c# - Entity Framework 一对多,每个层次结构一个表,为每个子类创建一个外键列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20892673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com