I am totally confused with update in EF. Tried to find related tutorial over internet but found nothing.
I have two question in mind.
- How to Update only specific field of some table.
-
How update works with navigational property?(i. if i update some entity then Ef(Linq to Entity) also update navigational property of it?)
[Table("master")] public class masterViewModel { [Key,ForeignKey("address")] public int id { get; set; } public string name { get; set; } public string lastName { get; set; } public virtual address address { get; set; } } public class address { [Key] public int id { get; set; } public string city { get; set; } public string state { get; set; }}
i.e suppose i have
[masterViewModel.id=1 , masterViewModel.name="ABC" and masterViewModel.lastName=null ] [address.id=1 , address.city="xyz" and address.state=null]then i at my view i did something like below
@Html.DisplayFor(modelModel => Model.name) @Html.DisplayFor(modelModel => Model.address.city) @Html.HiddenFor(x => x.id)@Html.HiddenFor(x => x.address.id) @Html.EditorFor(modelModel => Model.address.state ) @Html.EditorFor(modelModel => Model.lastName)
Because i used DisplayFor for name and string property i never gt value of these two field at my Controller action when form post, So i need something that that update only “state” (of address) and “lastName” (of masterViewModel) property.
One way is to us hidden fields for other properties as @Kyle suggested but it result in transporting unneeded properties from client to server and back. It also expose additional vulnerability because malicious client can create post request which will send modified
nameandcityas well so it will requires some additional validation logic on your server side.If you don’t want to update all properties you must tell it to EF. Suppose that you received your masterViewModel with related address with modified data to your controller’s action. Now you can do something like this:
Btw. in your case it looks like address can be complex type stored in your master table instead of separate entity.