使用entity framework更新实体,同时忽略某些属性

我正在使用asp.net mvc 4.我必须使用编辑方法更新我的持久性存储,但我想忽略一些列。

我在这里找到了一些答案,但他们并没有为我工作(我想)。

这是我的方法:

[HttpPost] public ActionResult Edit(Candidat candidat) { ProcRecDB _db = new ProcRecDB(); // from DbContext if (ModelState.IsValid) { _db.Entry(candidat).State = EntityState.Modified; _db.SaveChanges(); return RedirectToAction("Index"); } return View(candidat); } 

候选人模型有10个属性; 我怎么会忽略其中的一些?

如果您使用EF 5,则可以将属性标记为已修改后将其标记为未修改

 _db.Entry(candidat).State = EntityState.Modified; // Ignore changes to the value of SomeProperty _db.Entry(candidat).Property("SomeProperty").IsModified = false; _db.SaveChanges(); 

您可以创建一个新对象,将其附加到db上下文,然后只更新要保留的属性。

 [HttpPost] public ActionResult Edit(Candidat candidat) { ProcRecDB _db = new ProcRecDB(); // from DbContext if (ModelState.IsValid) { var updatedCandidat = new Candidat { Id = candidat.Id }; _db.Attach(updatedCandidat); // Set the properties that you would like to update. This must be // done after the object has been attached to the db context. updatedCandidat.FirstName = candidat.FirstName; updatedCandidat.LastName = candidat.LastName; ... _db.SaveChanges(); return RedirectToAction("Index"); } return View(candidat); } 

你在同一个位置有我。 我有类似的事情要做。

你必须选择:

您可以使用NotMapped(如果您不想存储任何值)。

但是我想你想要这个:

如果它是只读的,你不想修改那么你可以做类似的事情:

 var attachedEntity = this.context.Entry(orignalEntity); attachedEntity.CurrentValues.SetValues(updatedEntity); List excludeProperties = new List(); // Some of these fields you cannot just modify at all. excludeProperties.Add("UniqueIdentifier"); excludeProperties.Add("AuthorID"); excludeProperties.Add("DateCreated"); // You could even ask your dervived calls to tell which one to exclude // excludeProperties.AddRange(this.ExcludeUpdateProperties()); foreach (var name in excludeProperties) { var property = attachedEntity.Property(name); if (property != null) { attachedEntity.Property(name).IsModified = false; } } 

使用这种方法,而不是更新那些需要更新的字段,您可以使用attachmentEntity.CurrentValues.SetValues(updatedEntity),它将所有值设置为新值,然后您可以排除您想要的。 这种方法比逐个更新每个字段更好。