Context.saveChanges()修改已设置的外键

时间:2015-06-23 00:30:56

标签: asp.net-mvc-4 entity-framework-5 foreign-key-relationship savechanges

我有两个实体:

int wordCounter(char usStr[]) {
    int index= 0, punct= 0;

    while(usStr[index]!= '\0') {  // <<< Use effin' braces
        if(usStr[index]== ' ') { // <<< Use effin' braces
            index++;
        }
        else {
            break;
        }
    }

    // index points to a non ' ' character or '\0' here
    // No idea, what you're trying to achieve with the following lines
    // of code. 

    while(usStr[index] == '\0') { // If it's the end of the sentence ...
                                  // ... this part loops forever!
        punct++;
    }

    int allChar = punct + index;

    return allChar;
} 

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

当我尝试保留public class VideoModel { public int Id { get; set; } public string VideoFileName { get; set; } public DateTime UploadedTime { get; set; } public virtual UserProfile Owner { get; set; } } 实体时,会出现问题:

VideoModel

由SaveChanges()方法分配给 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 的新值大于先前尝试1中分配的值。当然,外键约束被破坏。为什么这个方法表现得如此奇怪?

1 个答案:

答案 0 :(得分:1)

如果EntityFramework找到您要求其搜索的UserProfile,那么您期望的行为就是它应该如何表现。

而目前可能发生的事情是EntityFramework无法通过usersContext.UserProfiles.Find(...)找到您要求的UserProfile;而是返回null。然后,在创建VideoModel时,它会创建一个新的UserProfile,以保持参照完整性。由于对用户名没有要求(例如长度应至少为8个字符或更多),因此可以创建新用户,而不会抛出任何异常。

为了测试这个理论,在创建新的VideoModel之后立即查询数据库中的UserProfile表。我很确定正在创建一个新的UserProfile。如果有一个被创建,那么请让我知道你找到了什么。

相关问题