Arman Hayots
Arman Hayots

Reputation: 2508

EF doesn't saving foreign data

Table Contact have *→1 relation to table Location via Location ID key. Following code saving all Contact data except Location. What I'm doing wrong? EF 6.0.0.0, MVC 5.2.3.0, but EF 4.4 and MVC 4 also causes this error.

using(MyEntities me = new MyEntities())
{
  Contact ct = me.Contact.SingleOrDefault(x=>x.User.UserID == WebSecurity.CurrentUserId);
  ct.Title = "sometitle"; //assignment and saving works
  ct.Location = me.Location.SingleOrDefault(x=>x.Location_ID == 19); //only assignment works
  me.SaveChanges();
}

I've disabled direct using of foreign keys when created EDMX model from database due to some errors.


Update: both Contact and Location have relation to User by UserID. Can this be source of the problem?

Upvotes: 0

Views: 35

Answers (1)

D4rkTiger
D4rkTiger

Reputation: 362

You must specify that Location level must be include in the context to be saved at the end.

So just add .Include("Location") in your code like this

using(MyEntities me = new MyEntities())
{
    Contact ct = me.Contact.Include("Location").SingleOrDefault(x=>x.User.UserID == WebSecurity.CurrentUserId);
    ct.Titile = "sometitle"; //assignment and saving works
    ct.Location = me.Location.SingleOrDefault(x=>x.Location_ID == 19); //only assignment works
    me.SaveChanges();
}

Upvotes: 2

Related Questions