c# - EF 6: Include not building navigation properties -
i cant seem figure out why navigation property not getting built include statement.
here method:
public async task<ihttpactionresult> getcompanies(string id) { dbcontext.database.log = s => system.diagnostics.debug.writeline(s); var company = await dbcontext.companies.where(x => x.id.tostring() == id).include(x => x.startelaccounts).firstordefaultasync(); if (company != null) { return ok(this.themodelfactory.create(company)); } return notfound(); }
when test sql debug log fields , values both objects.
here models:
public class companygroup { [key] public guid id { get; set; } [required] [maxlength(100)] public string name { get; set; } [required] [datatype(datatype.date)] public datetime firstbillingdate { get; set; } [required] public int termlength { get; set; } public virtual icollection<applicationuser> members { get; set; } public virtual icollection<accountstartel> startelaccounts { get; set; } public companygroup() { members = new hashset<applicationuser>(); startelaccounts = new hashset<accountstartel>(); } } public class accountstartel { [key] public guid id { get; set; } [required] public string clientid { get; set; } [required] public int dbid { get; set; } [required] public string name { get; set; } [required] public string timezone { get; set; } [required] public string accountnum { get; set; } public guid companyid { get; set; } public virtual companygroup company { get; set; } public virtual icollection<usagereport> usagereports { get; set; } public accountstartel() { company = new companygroup(); companyid = guid.empty; usagereports = new list<usagereport>(); } }
ef fluent api
modelbuilder.entity<accountstartel>() .hasrequired<companygroup>(x => x.company) .withmany(x => x.startelaccounts) .hasforeignkey(x => x.companyid); modelbuilder.entity<accountstartel>() .property(p => p.dbid) .isrequired() .hascolumnannotation( indexannotation.annotationname, new indexannotation( new system.componentmodel.dataannotations.schema.indexattribute("ix_starteldbid", 1) { isunique = true }));
can see im missing here?
could have setting company and/or companyid in accountstartel constructor? work if remove lines? – peter
initializing navigation properties default value caused ef not load them correctly.
here updated model work now
public class accountstartel { [key] public guid id { get; set; } [required] public string clientid { get; set; } [required] public int dbid { get; set; } [required] public string name { get; set; } [required] public string timezone { get; set; } [required] public string accountnum { get; set; } public guid companyid { get; set; } public companygroup company { get; set; } public virtual icollection<usagereport> usagereports { get; set; } public accountstartel() { usagereports = new list<usagereport>(); } }
Comments
Post a Comment