entity framework - DBContext simplest way to update foreign key -
var orgacc = db_.accounts.find(account.id); db_.entry(orgacc).currentvalues.setvalues(account); orgacc.company = db_.companys.find(account.company.id); db_.savechanges();
is simplest way update entity's association ?
public class chartofaccount: masterdata { [key] public int id { get; set; } [required] [stringlength(6)] public string code { get; set; } public virtual company company { get; set; } [required] public string accountname { get; set; } [required] [stringlength(3)] public string accountcurrency { get; set; } public virtual accountcatagory category1 { get; set; } public virtual accountcatagory category2 { get; set; } public string reference { get; set; } public bool hastransaction { get; set; } }
the way setvalues
works property-by-property compare, , each property left-hand object in argument, has matching type, update left-hand object value argument.
i presume account.company
different type of object orgacc.company
, such has come in mvc controller argument (ie account , it's referenced objects not ef entities). in case approach seems sound way of doing it.
that being said, orgacc
has company
property, , companyid
property, in order support ef relationships, so, if account
object followed same pattern, ie storing companyid
field directly, rather having navigate through company, setvalues automatically update companyid field, should update foreign key when save changes. way avoid step assigns orgacc.company
field.
Comments
Post a Comment