C# 为什么EF在表中插入重复项?
我的模型类如下所示:C# 为什么EF在表中插入重复项?,c#,entity-framework,C#,Entity Framework,我的模型类如下所示: 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<Ca
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;
}
}
在Package Manager控制台中执行(任意次数)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; }
}
然后在我执行
更新数据库之后
我得到了原本田、宝马和奥迪汽车的副本,但鉴别器设置为汽车
。为什么会这样?如何防止这种情况发生?您必须对所有种子对象进行如下测试
var car1 = context.Cars.FirstOrDefault(c => c.Make == " BMW ");
if(car1 == null)
{
context.Cars.Add(new Car { Id = 1, Make = "BMW", Model = "750i" });
}
您有重复项,因为对于实体框架,它们是不同的。 当您使用继承时,EF保留相同的表,但带有一个鉴别器。注意,如果没有继承,就没有鉴别器(不需要它) 您首先添加的汽车是真正的
汽车
类型,但由于继承不存在(目前),EF不会添加鉴别器。
当您添加Dragster
和JetCar
时,EF现在需要鉴别器
由于您第一次添加的汽车没有鉴别器,EF无法识别它们。现在,在查询Car
类型时,EF正在查找Discriminator='Car'
您可以更改种子脚本并手动调整一些数据(您可以在迁移中添加manuel查询,以添加Dragster
和JetCar
)
或者,您应该将继承交换为两个表之间的链接。谢谢,但是为什么EF在
更新数据库
命令时没有为已经存在的记录设置鉴别器呢?有什么原因吗?或者他们忘记实现这个功能了?因为EF不知道更新数据库之前是什么。这是你的工作来定义什么样的鉴别器应该是“旧”车。也许他们都是一种,也许他们都是另一种,也许两者都有。。。
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 }
);
}
var car1 = context.Cars.FirstOrDefault(c => c.Make == " BMW ");
if(car1 == null)
{
context.Cars.Add(new Car { Id = 1, Make = "BMW", Model = "750i" });
}