在使用Entity Framework时,我很难理解如何将项添加到列表中。 我的数据库已经创建并且表格在那里,但当我尝试通过种子方法添加选项时,我的选项表保持为空。
如何正确添加选项以便它们显示在我的数据库中并链接到正确的车辆?
我有2个型号:
车辆
public class VehicleModels
{
public virtual int Id { get; set; }
public virtual string Naam { get; set; }
public virtual string Merk { get; set; }
public virtual string Brandstof { get; set; }
public virtual string Kleur { get; set; }
public virtual string TypeVanMerk { get; set; }
public virtual string TypeVanTransmissie { get; set; }
public virtual int Kilometerstand { get; set; }
public virtual int Bouwjaar { get; set; }
public virtual int AantalDeuren { get; set; }
public List<Optie> Options { get; set; }
public VehicleModels()
{
Options = new List<Optie>();
}
public void AddOption(Optie optie) {
if (!Options.Equals(null))
{
Options.Add(optie);
}
}
}
选项
public class Optie
{
public virtual int OptieId { get; set; }
public virtual string Naam { get; set; }
public Optie(string naam)
{
Naam = naam;
}
}
这是我的种子/初始化器
public class VehicleDbInitializer : DropCreateDatabaseAlways<VehicleDB>
{
protected override void Seed(VehicleDB context)
{
context.VehicleModels.Add(new VehicleModels
{
Naam = "Auto 1",
Merk = "Audi",
Brandstof = "Benzine",
Kleur = "Rood",
TypeVanMerk = "A6",
TypeVanTransmissie = "Manueel",
Kilometerstand = 60000,
Bouwjaar = 2002,
AantalDeuren = 5
});
context.VehicleModels.Add(new VehicleModels
{
Naam = "Auto 2",
Merk = "BMW",
Brandstof = "Diesel",
Kleur = "Silver",
TypeVanMerk = "6",
TypeVanTransmissie = "Manueel",
Kilometerstand = 25000,
Bouwjaar = 2012,
AantalDeuren = 3
});
VehicleModels vehicle = new VehicleModels();
vehicle.Naam = "Auto 3";
vehicle.Merk = "Volvo";
vehicle.Brandstof = "Diesel";
vehicle.Kleur = "Silver";
vehicle.TypeVanMerk = "6";
vehicle.TypeVanTransmissie = "Manueel";
vehicle.Kilometerstand = 25000;
vehicle.Bouwjaar = 2012;
vehicle.AantalDeuren = 3;
vehicle.Options.Add(new Optie("Airco"));
vehicle.Options.Add(new Optie("Trekhaak"));
vehicle.Options.Add(new Optie("Airbags"));
context.VehicleModels.Add(vehicle);
base.Seed(context);
}
}
Global.aspx.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Database.SetInitializer(new VehicleDbInitializer());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
答案 0 :(得分:0)
您忘记在种子方法结束时拨打context.SaveChanges()
了吗?
答案 1 :(得分:-1)
您需要添加以下内容:
private List<Optie> tempList= new List<Optie>();
public List<Optie> Options
{
get
{
return tempList;
}
}
并删除以下内容:
public VehicleModels()
{
Options = new List<Optie>();
}
public void AddOption(Optie optie) {
if (!Options.Equals(null))
{
Options.Add(optie);
}
}