The foreign key does not update in an entity frame

advertisements

I have a class like

 public class Document
        {
            [Key]
            public int Id { get; set; }
            public User ModifiedBy { get; set; }
            public DateTime ModifiedDate { get; set; } 

        }

Here “User” is a class with some properties (all are primitive types ) Here is my mapping of class Document

HasRequired(a => a.ModifiedBy).WithMany().Map(b => b.MapKey("ModifiedBy")).WillCascadeOnDelete(false);

So in table "Document" ModifiedBy is a foreign key.

I am trying to update the ModifiedBy field of a document having id 10

Document  document=  new Document();
using (DBContext ctx = new DBContex())   {

    User loggedinUser =ctx.Users.Where(u=>u.LoginId==loggedInUserId).FirstOrDefault() as User;

    document.id=10;
    document.ModifiedBy = loggedinUser;
    document.ModifiedDate = DateTime.Now;
    ctx.Entry(document).State = EntityState.Modified;
    ctx.SaveChanges();
}

But the ModifiedBy field is not updating. only ModifiedDate field is updating.

Note that I don't what to update User table. I just want to update Document table


This is what I would do in your situation:

using (var ctx = new DBContext())   {

    var loggedinUser = ctx.Users.SingleOrDefault(u=>u.LoginId==loggedInUserId);

    if (loggedinUser == null) throw new Exception("Can't find logged in user");

    var document = ctx.Documents.SingleOrDefault(x => x.id == 10);

    if (document == null) throw new Exception("Can't find associated document");

    document.ModifiedBy = loggedinUser;
    document.ModifiedDate = DateTime.Now;

    ctx.SaveChanges();
}

Now the reason I do this.

When I do var document = ctx.Documents.SingleOrDefault(x => x.id == 10); I'm calling that particular entity into EF's change tracker. Which means if I change any of its properties such as ModifiedDate EF will automatically do ctx.Entry(document).State = EntityState.Modified;.

If you don't do this, and you want to carry on the way you do it, then you need to add this line (I believe):

document.ModifiedDate = DateTime.Now;
ctx.Documents.Attach(document);
ctx.Entry(document).State = EntityState.Modified;
ctx.SaveChanges();