Nikita Nikita - 1 year ago 53
C# Question

How to save item with navigation property to DB Entity Framework 6

public void Add(Site obj)
if(obj.Id == 0 || obj.Id >= 10000)
} else
Site dbEntry = context.Sites.Find(obj.Id);
if (dbEntry != null)
return res;

class Site {
public virtual List<Page> Pages { get; set; }

class Page {
public virtual Site Site {get;set;}

In Add method
Obj.Pages.Site(foreach of pages)
is null, but
not, I expected that when I save to DB
Site A
will be saved to DB too,and for each
navigation property Site
will be set to
. Pages are saving, but Site_Id in db is null. Should I create my own foreign keys or there is possibility to use entity-framework keys?

Answer Source

This code is valid. To find out the problem I've done the next:

1)add public int FieldId for each nav property
2)drop and recreate database
3)int is not nullable by default so now when try to add new record EF throws exception

In other words I make EF throws exception if it can't set navigation property, it helps me to find the error in my code(just set break point before crash and debug step by step). By default if it is not possible to set a navigation property EF set it to NULL