多個外鍵的表我有兩個子類型的超類型的「實體」,即「家用」和「連累機構」。插入到MVC與超類型/子類型的數據庫,第一個模型
我模仿他們作爲我的數據庫顯示在下面,他們被自動生成到EF模型(下文再次顯示)。
數據庫
EDMX模型
使用默認的腳手架MVC我可以添加一個新的家庭沒有任何問題。然而,當我嘗試添加一個新的涉案身體我當它試圖添加實體類型遇到錯誤。
只有相關(據我所知)兩種子類型之間的區別在於,家庭的實體類型被硬編碼爲「家庭」,而涉及身體的實體類型可以是任何實體類型,除了「家庭「 - 這是從用戶列表中選擇的。
對所涉及的身體HTTP POST創建操作拋出與和tEntityType被空tEntity和tEntityType之間的外鍵錯誤。代碼如下:
[HttpPost]
public ActionResult Create([Bind(Exclude = "entityID")]tEntity tentity
, tInvolvedBody tinvolvedbody
, tAddress taddress
, tAddressEntity taddressentity
//, tEntityType tentitytype
, int entityTypeID
)
{
#region entity type
//find entity type from id
var tentitytype = db.tEntityTypes.Find(entityTypeID);
#endregion
#region address
//assume start date of involved body not needed for reporting
taddressentity.startDate = DateTime.Now.Date;
#endregion
if (ModelState.IsValid)
{
db.tEntities.Add(tentity);
db.tInvolvedBodies.Add(tinvolvedbody);
db.tAddresses.Add(taddress);
db.tAddressEntities.Add(taddressentity);
db.SaveChanges();
return RedirectToAction("Index");
}
//recreate viewbag for entityType dropdown
var q = (
from e in db.tEntityTypes
where e.entityType != "Household"
select e
);
ViewBag.entityTypeID = new SelectList(q, "entityTypeID", "entityType");
return View(tinvolvedbody);
}
我試着加入tEntityType的參數列表的創建,但這導致ModelState.IsValid返回false因的EntityType正對所有對象空。
我也嘗試使用實體類型聯繫起來,積極向其他每個對象:
tentity.tEntityType = tentitytype;
tinvolvedbody.tEntity.tEntityType = tentitytype;
taddressentity.tEntity.tEntityType = tentitytype;
以上結束了工作,但它的每個其他對象的創建一個新的實體,即我得到三個在我tEntity表中的新行,一個是實體,一個鏈接tInvolvedBody和一個鏈接tAddressEntities。這是沒有意義的......
我如何可以插入創建一個實體,拿起實體類型,然後鏈接到AddressEntity結表的新InvolvedBody?
這將引發錯誤前,我是越來越指tEntity和tEntityType之間的外鍵約束。如果我在調試器中查看ModelState,它會將每個對象的tEntityType顯示爲NULL。 – melkisadek
@melkisadek您是否通過調試驗證了發送給控制器的EntityTypeID實際上是否與EntityTypeID匹配? – TNCodeMonkey
@TNCM - 是的,調試器爲EntityTypeID顯示正確的值。它不會做的是在沒有我特別添加實體類型的情況下導航EF模型,如原始文章中所示。如果我添加(取消註釋)tEntityType到創建參數列表,然後我得到關鍵「entityType」的無效模型。如果我取消註釋將entityTypes鏈接到每個對象的代碼,那麼我仍然會獲得更多行。 – melkisadek