【发布时间】:2017-01-20 23:02:25
【问题描述】:
我的模型类如下所示:
public class Car {
public int Id { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}
ApplicationDbContext 类:
public class ApplicationDbContext : DbContext {
public DbSet<Car> Cars { get; set; }
public ApplicationDbContext()
: base("Rental") {
Configuration.LazyLoadingEnabled = true;
}
}
和种子方法:
protected override void Seed(ApplicationDbContext context) {
context.Cars.AddOrUpdate(c => c.Id,
new Car { Id = 1, Make = "BMW", Model = "750i" },
new Car { Id = 2, Make = "Audi", Model = "A6" },
new Car { Id = 3, Make = "Honda", Model = "Civic" }
);
}
在我在包管理器控制台中执行(任意多次)update-database 之后,这些对象一旦添加到数据库中。
但是在我添加了 Car 类的子类之后:
public class Car {
public int Id { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public virtual ICollection<Rental> Rentals { get; set; }
}
public class JetCar : Car {
public int Thrust { get; set; }//kN
}
public class Dragster : Car {
public double Acceleration { get; set; }
}
然后修改ApplicationDbContext:
public class ApplicationDbContext : DbContext {
public DbSet<Car> Cars { get; set; }
public DbSet<JetCar> JetCars { get; set; }
public DbSet<Dragster> Dragsters { get; set; }
public ApplicationDbContext()
: base("Rental") {
Configuration.LazyLoadingEnabled = true;
}
}
然后是种子方法
protected override void Seed(ApplicationDbContext context) {
context.Cars.AddOrUpdate(c => c.Id,
new Car { Id = 1, Make = "BMW", Model = "750i" },
new Car { Id = 2, Make = "Audi", Model = "A6" },
new Car { Id = 3, Make = "Honda", Model = "Civic" }
);
context.Dragsters.AddOrUpdate(d => d.Id,
new Dragster { Id = 4, Make = "Chevy", Acceleration = 3.23, }
);
context.JetCars.AddOrUpdate(d => d.Id,
new JetCar { Id = 4, Make = "Jetty", Thrust = 89 }
);
}
然后在我执行update-database 之后,我最终得到了原始本田、宝马和奥迪汽车的副本,但鉴别器设置为Car。为什么会这样?如何预防?
【问题讨论】:
标签: c# entity-framework