基本上我想要一个包含Owner详细信息的视图。Owner可以有多种类型的Vehicle (或没有),可以使用 Checkbox 进行选择:
提交时,必须更新数据库,因为下次在视图中显示所有者时,所有者必须选中正确的复选框。
我不确定如何构建我的 EF 模型,也不确定我是否正确链接它以获得我想要的结果。
我不想将车辆类型作为字段硬编码到Owner对象中,因为有大量车辆。
谁能指出我如何链接这些模型的正确方向?我需要数据库中的两个或三个表吗?
这是我目前所拥有的,但它可能是错误的。如果您有任何想法,请立即停止阅读以避免混淆。 欢迎任何意见!
型号:
public class Vehicle
{
public int VehicleID { get; set; }
public string Name { get; set; }
}
public class Owner
{
public int OwnerID { get; set; }
public string Name { get; set; }
public virtual ICollection<OwnerVehicle> OwnerVehicles { get; set; }
}
public class OwnerVehicle
{
public int OwnerVehicleID { get; set; }
public bool Ticked { get; set; }
//Not sure if this is needed, because ticked will always be true
//I delete OwnerVehicle if not needed
public int OwnerID { get; set; }
public virtual Owner Owner { get; set; }
public int VehicleID { get; set; }
public virtual Vehicle Vehicle { get; set; }
}
控制器 :
public ActionResult Index()
{
//prepopulate Owner objects on the fly for this example, in my project it would fetched/created with EF into database
Owner owner = getOwner();
return View(owner); // we return the owner to view
}
public Owner getOwner()
{
//Create a owner
Owner owner = new Owner() { OwnerID = 1, Name = "JACK" };
//Create a list of vehicles
List<Vehicle> Vehicles = new List<Vehicle>();
Vehicles.Add(new Vehicle() { VehicleID = 1, Name = "I have a car"});
Vehicles.Add(new Vehicle() {VehicleID = 1, Name = "I have a bike" });
//the owner doesnt have any vehicles yet, therefor object OwnerVehicle is null at the moment
return owner;
}
[HttpPost]
public ActionResult Index(Owner owner)
{
//at this point, the owner needs have his list of Vehicles linked, and written to database
//
//ToDO
//return View();
}
下面的视图不会编译,因为我迷路了。
索引.cshtml
@model Owner
@using (Html.BeginForm())
{
<div class="editor-field">
@Html.EditorFor(model => model.OwnerVehicles)
</div>
}
EditorTemplates/OwnerVehicles.cshtml
@model OwnerVehicle
<div>
@Html.CheckBoxFor(x => x.Ticked)
@Html.LabelFor(x => x.TODO, Model.TODO)
@Html.HiddenFor(x => x.TODO)
</div>