DatabaseContext延迟更新数据库

时间:2018-01-28 07:33:48

标签: wpf entity-framework dbcontext

使用Code First EF时遇到问题。当我想插入具有权限的用户时,用户插入很好,但是在插入用户之后插入权限时,我看到了这个例外:

SqlException:INSERT语句与FOREIGN KEY约束“FK_dbo.UserPermissions_dbo.Users_UserId”冲突。冲突发生在数据库“DATABASE”,表“dbo.Users”,列'UserId'。

这是我的代码:

public class User
{
    public short UserId { get; set; }
    public string  Username { get; set; }
    public string Password { get; set; }
    public ObservableCollection<UserPermission> UserPermissions { get; set; }
}

public class UserPermission
{
    public int UserPermissionId { get; set; }
    public short UserId { get; set; }
    public short PermissionEnum { get; set; }
    public bool IsPermitted { get; set; }
}

public class DatabaseContext : DbContext
{
    public DatabaseContext()
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<UserPermission> UserPermissions { get; set; }
}

要插入的最终代码是:

    private void ConfirmButton_Click(object sender, RoutedEventArgs e)
    {
        var user = new User { Username = "myUsername", Password = "12"};

                    using (var dbContext = new DatabaseContext())
        {
            dbContext.Users.AddOrUpdate(user);
            dbContext.SaveChanges();
        }

        SaveUserPermissions(user);

    }

    private void SaveUserPermissions(User user)
    {


        var userPermissionsToSave = new ObservableCollection<UserPermission>();

        foreach (var permission in ThisUserPermissionData.UserPermissions)
        {
                var newUserPermission = new UserPermission();

                newUserPermission.UserId = PageModel.UserId;
                newUserPermission.UserPermissionTypeEnum = 4;                    
                userPermissionsToSave.Add(newUserPermission);

        }

        using (var dbContext = new DatabaseContext())
        {
            dbContext.UserPermissions.AddOrUpdate(userPermissionsToSave.ToArray());
            dbContext.SaveChanges();
        }
    }

请注意,在保存用户后设置断点时,代码执行正常。但在正常模式下,我的代码有异常。

提前致谢。

0 个答案:

没有答案