私のモデルクラスは、そのようになります。EFが重複をテーブルに挿入したのはなぜですか?
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
これらのオブジェクトは、パッケージマネージャコンソールでデータベースに一旦追加されます。私は終わったupdate-database
を実行した後、次に
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 }
);
}
:
しかし、私は車のクラスのサブクラスを追加した後:その後、
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を修正しましたホンダ、BMW、アウディの2台のオーディオーイミネーターをCar
に設定します。それはなぜそうですか?これを防ぐ方法は?
ありがとうございます、なぜ、EFが 'update-database'コマンドで既存のレコードのための識別子を設定しなかったのですか?その理由はありますか、この機能を実装するのを忘れていましたか? – Yoda
EFは更新データベースの前に何があったのか分からないためです。 Discriminatorが「古い」自動車であるべきものを定義することはあなたの仕事です。たぶん彼らは1つのタイプ、多分彼らは他のすべての、多分いくつかの両方があります... –