[Solved] Update Models in Controller with Linq to Sql [closed]


You could write your own implementation by iterating through properties with reflection (e.g. konut.GetType().GetProperties() and then iterate through all properties and setting them for Db model) or you could use some 3rd party tools to do mapping for you. For example AutoMapper (https://automapper.org/) or ValueInjecter (https://github.com/omuleanu/ValueInjecter). They both do pretty good job, although I think ValueInjecter is simpler to begin with.

Here you have sample when using ValueInjecter:

[HttpPost]
public ActionResult KonutGuncelle(Konut konut, KonutOzellik ko)
{
    KonutOzellik willBeUpdatedko = ctx.KonutOzellik.SingleOrDefault(x => x.KonutOzellikID == konut.KonutOzellikID);
    willBeUpdatedko.InjectFrom(ko); // New code with ValueInjecter

    Konut willBeUpdatedkonut = ctx.Konut.SingleOrDefault(x => x.id == konut.id);
    willBeUpdatedko.InjectFrom(konut); // New code with ValueInjecter

    ctx.SaveChanges(); // Must save changes?

    return RedirectToAction("KonutGuncelle", new { konut.id });
}

1

solved Update Models in Controller with Linq to Sql [closed]