簡體   English   中英

嘗試使用entry.GetDatabaseValues()。ToObject()檢索導航屬性時,“ NullReferenceException未由用戶代碼處理”

[英]“NullReferenceException was unhandled by user code” when trying to retrive a navigation property using entry.GetDatabaseValues().ToObject()

我有以下操作方法:

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Rack rack)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    repository.InsertOrUpdateRack(rack);
                    repository.Save();
                    return RedirectToAction("Index");
                }

            }
            catch (DbUpdateConcurrencyException ex)
            {
                var entry = ex.Entries.Single();
                var databaseValues = (Rack)entry.GetDatabaseValues().ToObject();
                var clientValues = (Rack)entry.Entity;


                if (databaseValues.RU != clientValues.RU)
                    ModelState.AddModelError("RU", "Current value: "
                        + databaseValues.RU);
                if (databaseValues.DataCenterID != clientValues.DataCenterID)
                    ModelState.AddModelError("DataCenterID", "Current value: "
                        + databaseValues.DataCenter.Name);
                if (databaseValues.ZoneID != clientValues.ZoneID)
                    ModelState.AddModelError("ZoneID", "Current value: "
                        + databaseValues.Zone.Name);

但是,如果引發DbUpdateConcurrncy異常,我將在databaseValues.DataCenter.NamedatabaseValues.Zone.Name上獲得Null引用異常。 看來我無法從Getdatabase().Toobject訪問兩個導航屬性(Datacenter和Rack Getdatabase().Toobject任何想法如何解決此問題?

我在這里也給出了這個答案但由於其他問題出現在我的Google搜索的第一頁上,因此為了方便他人,在此處復制了此答案:

我要離開這里的是,在嘗試處理並發問題之類時仍然偶然發現此問題的任何人。

當前,當ToObject方法使用最新的數據庫值填充實體時,它不會從數據庫填充該實體的導航屬性。 這在某種程度上是可以接受的,因為導航屬性可能具有應手動處理的添加/刪除。 還請記住,實體是分離的

我還沒有真正找到一種方法來由EF自動填充這些值。 您可能必須對感興趣的每個屬性使用“ GetValue”方法,然后自己填充它們。

這是一個類似偽代碼的解決方案:

DbEntityEntry entry = context.Entry(yourEntity);
//Gets latest values of entity from the database
var propertyValues = entry.GetDatabaseValues();
//Fills an entity object with database values(except navigational properties)
dynamic newEntity = propertyValues.ToObject();
//Manually loading the needed navigational properties and handling add/removes.
foreach (var prop in propertyValues.PropertyNames)
{
    //either a collection<int> or an int.
    var idOfReferencedElement = propertyValues.GetValue<int>(foreignKeyField);
    //remember to handle add/removes too.
    newEntity.[thePropertyYouKnowExist] = context.[theDBSet].Local.Find(idOfReferencedElement);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM