entity framework - EF Navigation Properties and Saves -
suppose have these 2 pocos:
public class album { public int id { get; set; } [required] public string title { get; set; } public short rating { get; set; } public int artistid { get; set; } [required] public virtual artist artist { get; set; } } public class artist { public int id { get; set; } [required] public string name { get; set; } public virtual icollection<album> albums { get; set; } }
and execute code this:
using (pickcontext db=new pickcontext()) { album pick=db.albums.singleordefault(a => a.id==pickid); if (pick==null) return; pick.rating=4; db.savechanges();
i surprised got validation exception this:
property: "artist", error: "the artist field required."
when changed query include artist:
album pick=db.albums.include("artist").singleordefault(a => a.id==pickid);
i no longer got exception. if don't tell ef populate properties, , they're not required, overwrite these fks in database? have thought if retrieve entity , don't assign property, property won't changed in database. not true?
you don't need use required attribute artist. telling ef navigation property required there. since have defined,
public int artistid { get; set; }
as not nullable artistid required in in database level (i think expected required attribute here). think can remove required attribute , should working expected.
Comments
Post a Comment