Update an entity using entity framework while ignoring some properties

后端 未结 3 1658
Happy的楠姐
Happy的楠姐 2020-12-06 15:01

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.

I had found some answers here, but t

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 15:07

    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 ).

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

    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. This approach is nicer than updating each field one by one.

提交回复
热议问题