Tjaart
Tjaart

Reputation: 4119

Navigation properties get lost when updating entity

I'm trying to save an object using EF 7 but when I try to update it my foreign key values (navigation properties) get lost. The foreign keys are all null in the database after running the code below.

 UserTask s = new UserTask()
        {
            Id = 10027,
            Description ="test change",
            Title = "Test change",
            DueDate = DateTime.Now.AddHours(3),
            CreatedBy = db.Users.Where(c=>c.UserName=="Bob").First(),
            AssignedTo = db.Users.Where(c => c.UserName == "Stephen").First(),
            Status = stat
        };

        db.UserTasks.Attach(s);

        db.Entry(s).State = EntityState.Modified;
        db.SaveChanges();

Upvotes: 0

Views: 385

Answers (1)

AiApaec
AiApaec

Reputation: 660

You are not setting FKs in variable "s", for example s.Fk1Id, so that field will be null. First get the instance from EF:

var s = db.UserTasks.Where(o=>o.Id=="10027").First();

s.Id = 10027;
s.Description ="test change";
s.Title = "Test change";
s.DueDate = DateTime.Now.AddHours(3);
s.CreatedBy = db.Users.Where(c=>c.UserName=="Bob").First();
s.AssignedTo = db.Users.Where(c => c.UserName == "Stephen").First();

Upvotes: 1

Related Questions