代码之家  ›  专栏  ›  技术社区  ›  Graham Conzett

使用实体密钥伪造外键更新

  •  6
  • Graham Conzett  · 技术社区  · 17 年前

    在里面 Alex James' Entity Framework tips articles how to fake foreign key properties . 这似乎正是我所需要的,但无论出于什么原因,我似乎无法在更新时完成它。我的控制器的更新部分中有以下内容:

    [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(candidates candidateToEdit)
        {
            string EduIDValue = candidateToEdit.education.ID.ToString();
    
            if (!ModelState.IsValid)
                return View();
    
            try
            {
                var originalCandidate = (from c
                                                in model.candidates
                                                where c.ID == candidateToEdit.ID select c).FirstOrDefault();
    
                //attempting it here
                originalCandidate.educationReference.EntityKey = new System.Data.EntityKey("model.education", "ID", candidateToEdit.education.ID);
    
                model.ApplyPropertyChanges(originalCandidate.EntityKey.EntitySetName, candidateToEdit);                
                model.SaveChanges();
                return RedirectToAction("Index");
            }
            catch(Exception e)
            {
                Response.Write("Education ID Value " + EduIDValue + "<br /><br />Error: <br /><br />" + e);
                return null;                
                //return View();
            }
        }
    

    这样做失败,并会产生以下结果:

    System.ArgumentException:元数据集合中不存在标识为“model”的成员。参数名称:System.Data.Metadata.Edm.MetadataCollection处的标识 1.GetValue(String identity, Boolean ignoreCase) at System.Data.Metadata.Edm.ReadOnlyMetadataCollection 1.System.Data.Metadata.Edm.ItemCollection.GetEntityContainer(字符串名称,布尔ignoreCase)处System.Data.Metadata.Edm.ItemCollection.GetEntityContainer(字符串名称,布尔ignoreCase)处System.Data.Metadata.Edm.MetadataWorkspace.GetEntityContainer(字符串名称,数据空间数据空间)位于System.Data.Objects.DataClasses.EntityReference.set\u EntityKey(EntityKey值)处的System.Data.EntityKey.GetEntitySet(MetadataWorkspace MetadataWorkspace)处位于System.Data.Objects.DataClasses.EntityReference.set\u EntityKey(EntityKey值)处位于InternicshipTest.Controllers.CandidatesController.Edit(CandidatesCandidatesToEdit)在C:\Documents and Settings\graham\My Documents\Visual Studio 2008\Projects\InternishipTest\InternishipTest\Controllers\CandidatesController.cs中:第84行

    这对我来说毫无意义,model绝对是EntitySet的名称。

    1 回复  |  直到 17 年前
        1
  •  4
  •   Graham Conzett    17 年前

    我知道了,事实上我的实体设置不正确。在创建新实体键时,我通过将以下参数作为第一个参数来绕过它:

    originalCandidate.educationReference.EntityKey = new System.Data.EntityKey(originalCandidate.educationReference.EntityKey.EntityContainerName + "." + originalCandidate.educationReference.EntityKey.EntitySetName, "ID", candidateToEdit.education.ID);
    

    有点恶心,但它有效。 期待在.NET4.0中整理EF中的外键混乱

    推荐文章