简体   繁体   English

使用实体框架更新实体,同时忽略某些属性

[英]Update an entity using entity framework while ignoring some properties

I am working with asp.net mvc 4. I have to update my persistence store using an edit method, but I want to ignore some columns.我正在使用 asp.net mvc 4。我必须使用编辑方法更新我的持久性存储,但我想忽略一些列。

I had found some answers here, but they weren't working for me (I suppose).我在这里找到了一些答案,但它们对我不起作用(我想)。

Here is my method:这是我的方法:

[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);
}

The Candidate model has 10 properties;候选模型有 10 个属性; how would I ignore some of them?我将如何忽略其中一些?

If your using EF 5, you can mark a property as not modified after its been marked as modified如果您使用 EF 5,则可以在将属性标记为已修改后将其标记为未修改

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

You can create a new object, attach it to the db context, then update just the properties you want to be persisted.您可以创建一个新对象,将其附加到 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);
}

You are in same position has me.你在同一个位置有我。 I have similar things to do.我有类似的事情要做。

You have to options:你必须选择:

You can use NotMapped (in case you don't want to store any value ).您可以使用 NotMapped (以防您不想存储任何值)。

However I think you want this:但是我认为你想要这个:

if it is readonly, and you don't want to modify then you can do something similar:如果它是只读的,并且您不想修改,那么您可以执行类似的操作:

var attachedEntity = this.context.Entry(orignalEntity);
                    attachedEntity.CurrentValues.SetValues(updatedEntity);

    List<string> excludeProperties = new List<string>();

                        // 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;
                            }
                        }

with this approach, rather than updating those fields that needs to be updated you can use attachedEntity.CurrentValues.SetValues(updatedEntity) which will set all value as new value, and then you can exclude that you want to.使用这种方法,您可以使用 attachEntity.CurrentValues.SetValues(updatedEntity) 而不是更新那些需要更新的字段,它将所有值设置为新值,然后您可以排除您想要的。 This approach is nicer than updating each field one by one.这种方法比一个一个地更新每个字段要好。

Say you have an object with 10 properties and you only want to update one.假设您有一个具有 10 个属性的对象,而您只想更新一个。 First, as expected, the client-side .cshtml form should only contain the field(s) you are updating as well as the ID.首先,正如预期的那样,客户端的 .cshtml 表单应该只包含您正在更新的字段以及 ID。 Secondly, in the post method do the following:其次,在 post 方法中执行以下操作:

// Form Data Model
public Candidate FormCandidate {get; set;}

public IActionResult OnPostCanidata() {
    var _update = _context.Candidate.Find(Id);
    _update.SomeProperty = FormCandidate.SomeProperty;
    _context.SaveChanges();
}

I prefer this method over the "Property/isModified" approach because if 9 out of 10 fields don't get updated that's a lot of extra server side code to write.我更喜欢这种方法而不是“Property/isModified”方法,因为如果 10 个字段中有 9 个没有得到更新,那么需要编写大量额外的服务器端代码。 Also if the data model changes and additional read-only properties are added, you won't need to re-visit the code and specify their Property/isModified=fasle.此外,如果数据模型发生更改并添加了其他只读属性,则无需重新访问代码并指定其 Property/isModified=fasle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM