Foreign key not updating in entity frame work

116 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

Base on Entity Framework does not update Foreign Key object I created

public string ModifiedBy { get; set; }

[DataMember]
[ForeignKey("ModifiedBy")] 
public User ModifiedUser
        {
            get;
            set;
        }

That means I additionally introduced a primitive type(string ModifiedBy ) for Modified User and specified ForeignKey. That resolved my issue

3
On

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();