c# - Entity Framework 6 navigation collections are null instead of empty -


i'm trying write relational database application using entity framework 6. have classes analogous to:

public class subject {     public int id { get; set; }     public string name { get; set; }     public virtual icollection<student> students { get; set; } }  public class student {     public int id { get; set; }     public int subjectid { get; set; }     public string name { get; set; }     public virtual subject subject { get; set; } } 

(ok bad example because in reality you'd want each student in more 1 subject let's ignore best example think of.)

the problem that, whenever there's subject no students, instead of subjectinstance.students returning empty collection instead returns null. means cannot call subjectinstance.students.add(studentinstance) add first student. instead have add student separately, calling contextinstance.students.add(studentinstance) after manually setting subjectid field on studentinstance. once there's 1 or more students associated subject, subjectinstance.students no longer null , can add further students in expected way.

what i've tried:

  • removing virtual public virtual icollection<student> students { get; set; } - no change

  • calling contextinstance.entry(subjectinstance).collection("students").load() before attempting access collection - works it's messy , breaks separation of concerns (the modules work data shouldn't have concern loading data)

  • calling contextinstance.subjects.include("students") @ point before creating subjectinstance - no change

as official documentation demonstrates, should initialize collection navigation properties inside entity constructor if want prevent null reference exception.

public subject() {     students = new hashset<student>(); // may use list<student>, hashset guarantee not adding same student 2 times mistake } 

entity framework fill students property (using proxy) if there @ least student, else leave property (null if have not initialized it).

when entity not proxy, entity framework tracks changes when calling savechanges() on context, using original entity state comparison. this answer further clarify behavior.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -