c# - How to exclude the child object when saving a parent to EF? -


i have nullable foreign key parent child:

public class company {     public int? addressid {get;set;}     public address address {get;set;} }  public class address {     public string streetaddress {get;set;} //not nullable in db } 

when try , save database ef tries save address object despite being null:

var company = new company{addressid = null } //other stuff populated matters  try {     _context.entry(company).state = entitystate.added;     _context.savechanges(); } catch (exception exception) {     //throws validation error because streetaddress not nullable } 

i tried these

{     _context.entry(company).state = entitystate.detached;     _context.company.add(company); }  {     _context.companies.add(company); } 

both of them still require street address populated.

how can ignore nullable children when saving?

i have hunch child foreign key non-nullable. try setting property virtual:

public virtual address address { get; set; } 

Popular posts from this blog