c# - Update Unique property entity framework -
public class person { [required] public int? kupaid { get; set; } [foreignkey("kupaid")] public kupa kupa { get; set; } public int? newkupaid { get; set; } [foreignkey("newkupaid")] public kupa newkupa { get; set; } } public class kupa { public int id { get; set; } [index("ix_uniqueid", isunique = true)] public int ? uniqueid { get; set; } } public class mycontroller:controller { public json editkupa(expression<func<person,bool>> criteria ) { using (ikupotrepository<person> _ipersonrepository = new sqlrepository<person>()) { person persontoedit=_ipersonrepository.singleordefault(criteria,getincludeproperties()); > //getting new kupa obj db newkupa = getkupa(uniqueid); <//changing unique property null persontoedit.kupa.toremid = null; persontoedit.kupa.state = state.modified; persontoedit.newkupa = newkupa; >//assign unique id property value in first kupa persontoedit.newkupa.toremid = 1; persontoedit.newkupaid = newkupa.id; persontoedit.newkupa.state = state.modified; _ipersonrepository.savechanges(); } } when calling savechanges() getting exception :unique key violation , when looking @ sql profiler can see ef 6 generates update query both kupa object tries update newkupa.uniqueid before updating kupa.uniqueid ?
assuming using sql server database server happening because allow null values in column , null = null null if have multiple rows null on column you'll error.
to implement in sql statements this:
create unique nonclustered index idx_uniqueid_notnull on kupa(uniqueid) uniqueid not null; however, in ef there no easy way, there workaround in answer here.
Comments
Post a Comment