Context.saveChanges() modifies foreign key that has already been set

128 views Asked by At

I have two entities:

public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
}

and

public class VideoModel
{
    public int Id { get; set; }
    public string VideoFileName { get; set; }
    public DateTime UploadedTime { get; set; }
    public virtual UserProfile Owner { get; set; }
}

When i trying to persist VideoModel entity, the problem appears:

     VideoModel video = db.VideoModels.Create();
            video.VideoFileName = fileName;
            video.Owner = usersContext.UserProfiles.Find(WebSecurity.CurrentUserId); // CurrentUserId = 3, ok
            video.UploadedTime = DateTime.Now; // video.Owner.UserId = 3
            db.VideoModels.Add(video); // still 3 
            db.SaveChanges(); // Problem! video.Owner.UserId = 10

And the new value assigned to UserId by SaveChanges() method is greater than the value assigned in previous attempt on 1. Of course the foreign key constraint is broken. Why the method behaves in such a strange way?

1

There are 1 answers

0
Parth Shah On

If EntityFramework finds the UserProfile that you have asked it to search for, then the behavior you are expecting is how it should behave as.

Instead what could be happening at the moment is EntityFramework cannot find the UserProfile that you are asking via usersContext.UserProfiles.Find(...); and instead returns null. It then creates a new UserProfile while creating the VideoModel in order to maintain the referential integrity. Since there are no requirements on Username (such as length should be at least 8 characters or more), it is able to create a new user without any exception being thrown anywhere.

In order to test this theory out, query your UserProfile table in the database immediately after your new VideoModel is created. I am pretty certain a new UserProfile is being created. If there is one being created, then please let me know what you find.