我在這個問題上看到了很多問題,但我找不到幫助我的問題,我嘗試在建築物和房間之間創建一對多關係,即一個建築物與許多房間。據我所知,我的ICollection <>值沒有被髮送到我的數據庫。我使用局部視圖在建築物內部創建房間,我的建築物模型包含Icollection,而我的房間模型包含建築物ID。但是,當我創建一個房間時,它不會將buildingId與ICollection值相關聯。使用實體框架創建一對多關係的問題
這裏是我的模型的建築和房間都:
public class buildingInfo
{
public int Id { get; set; }
public int buildingNumber { get; set; }
public String buildingName { get; set; }
public String buildingAddress { get; set; }
public String buildingDesc { get; set; }
public virtual ICollection<roomInfo> curRooms { get; set; }
}
public class roomInfo
{
public int Id { get; set; }
public int roomNumber { get; set; }
public String roomName { get; set; }
public String roomLocation { get; set; }
public String roomDesc { get; set; }
public int buildingId { get; set; }
}
這房間查看:
@model TerminalHost.Models.buildingInfo
@{
ViewBag.Title = "Home Page";
}
<h3>Rooms in: @Model.buildingName</h3>
<ol class="round">
<li class="one">
<h5>Please begin creating your network structure:</h5> <button id="modal-opener">Add a new room</button>
</li>
</ol>
@Html.Partial("rooms", Model.curRooms)
<div id="Modal" title="Room Details">
@Html.Partial("roomForm", new TerminalHost.Models.roomInfo { buildingId = Model.Id })
</div>
下面是發生在室內形式詳情:
@model TerminalHost.Models.roomInfo
<h2>Create</h2>
@using (Html.BeginForm("roomForm","Home"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>roomInfo</legend>
<div class="editor-label">
@Html.Label("Room Number:")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.roomNumber)
@Html.ValidationMessageFor(model => model.roomNumber)
</div>
....
<div style="visibility: hidden">
<div class="editor-field">
@Html.TextBoxFor(model => model.buildingId)
@Html.ValidationMessageFor(model => model.buildingId)
</div>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
這些是處理房間局部視圖的方法:
[HttpGet]
public ActionResult roomForm(int buildingId)
{
return PartialView();
}
//Here the data from the room form is inserted to the database
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult roomForm(roomInfo roominfo)
{
//roominfo.
if (ModelState.IsValid)
{
_db.rooms.Add(roominfo);
_db.SaveChanges();
return RedirectToAction("room", new {id = roominfo.buildingId});
}
return PartialView(roominfo);
}
這裏是的DbContext:
public class thDB : DbContext
{
public DbSet<buildingInfo> buildings { get; set; }
public DbSet<roomInfo> rooms { get; set; }
public DbSet<deviceInfo> devices { get; set; }
public DbSet<rackInfo> rackInfoes { get; set; }
}
如果有任何進一步的信息需要請詢問。
你buildinginfo類應該有一個構造函數初始化roomInfo的列表。 curRooms = new List(); –
heymega
贊同:public列表 curRooms =新列表(); –
ValMangul
我會添加我的答案。 – heymega