简体   繁体   中英

Updating partial entity using Entity Framework (with razor view)

I have an entity:

public class Organization
{
    public int OrganizationId { get; set; }
    [Required]
    [StringLength(160)]
    public string Name { get; set; }
    public DateTime? CreatedOn { get; set; }
    public DateTime? ModifiedOn { get; set; }
    public virtual ICollection<Team> Teams { get; set; }
    public virtual ICollection<ApplicationUser> Persons { get; set; }
}

I have created a OrganizationViewModel for representing data to view as well as creating new entities. I later map it using Automapper before saving changes to database using Entity Framework...

public class OrganizationViewModel
{
    public int OrganizationId { get; set; }
    [Required]
    [StringLength(160)]
    public string Name { get; set; }
    public List<ApplicationUser> Persons { get; set; }
}

I have created an action method Edit which should only allow user to edit property Name (for this example only, but in reality, it does update many other properties which I have slimmed down for this question)..

The Edit view only has two properties @Html.HiddenFor(model => model.OrganizationId) and @Html.EditorFor(model => model.Name)

Now in [HttpPost]

I got OrganizationViewModel with updated Name property but property Persons remains null, if there are users already present in an organization EF throws an error as it is not expected by the context.

I could have updated the properties I want to update EXPLICITLY in Post method but I don't want to do everything manually. Is there any other way where I can say that just update the entities I want. I tried using Bind 's Include and Exclude but it has null for Persons as well.

Help me :)

If you create a view model that contains only the OrganizationId and Name properties that are edited by this view, you can achieve it by executing

db.Entry(db.Organizations
  .First(x => OrganizationId == viewModel.OrganizationId))
  .CurrentValues.SetValues(yourViewModel);

yourViewModel - can be any object with set of properties that you want to update, so you don't need to repeat your code but you have to have a specific view model for each operation. You may have it even locally for the update method and automap to it but it must have only properties you want to update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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