MySQL Entity Framework 6更新影响所有行代码优先

时间:2018-06-24 10:08:32

标签: c# mysql database entity-framework entity-framework-6

我正在将Entity Framework 6与MySQL配合使用。

插入很好,我能够插入一条新记录。但是当我尝试更新新创建的记录时。它将更新所有行。

这是我要保存的代码。

    // This is the method I use every time I save a record.
    public async Task SaveAsync(User model)
    {

        if (model.Id != 0)
        {
            var original = GetOriginal(model.Id);

            if (model.Password == string.Empty)
            {
                model.Password = original.Password;
            }
            // The state is always modified if I'm updating the record.
            var state = Context.Entry(model).State;
        }


        await base.SaveAsync();
    }

当我保存要更新的记录时,这是更新查询。实体框架使用User_Update存储过程,但是缺少where子句,这就是更新影响所有行的原因。

`User_Update`
-- Id: '6' (Type = Int32, IsNullable = false)
-- Username: 'test123' (Type = String, IsNullable = false, Size = 7)
-- Password: 'vZxTTTgLiQUxwchySt1e1o/I9XMWm4QW5pO6MpPGI0o=' (Type = String, IsNullable = false, Size = 44)
-- Email: 'test1@gmail.com' (Type = String, IsNullable = false, Size = 15)
-- FullName: 'test1' (Type = String, IsNullable = false, Size = 5)
-- CreatedAt: 'null' (Type = DateTime, IsNullable = false)
-- UpdatedAt: 'null' (Type = DateTime, IsNullable = false)
-- RoleId: '2' (Type = Int32, IsNullable = false)
-- Executing asynchronously at 
-- Completed in 9 ms with result: 6

更新: 添加了执行SaveAsync的SaveCommand

        private async void SaveCommandExecute(object obj)
    {
        //var passwords = (Tuple<string, string>) obj;
        //var password = passwords.Item1;
        //var confirmPassword = passwords.Item2;

        var result = await DialogHelper.ShowAsync("Are you sure you want to continue?", "Confirmation",
            MessageDialogType.YesNo);

        if (result)
        {
            await UserWrapper.ValidateAll();

            if (!UserWrapper.HasErrors)
            {

                if (UserWrapper.Id == 0)
                {
                    UserWrapper.Password = DbHelper.CalculateHash(UserWrapper.FakePassword, UserWrapper.Username);
                }

                await _userRepository.SaveAsync(UserWrapper.Model);
                HasChanges = false;
                Id = UserWrapper.Id;
                SetTitle();
                ((DelegateCommand<object>)SaveCommand).RaiseCanExecuteChanged();


                await LoadAsync(UserWrapper.Id);
            }

        }

    }

现在我的问题是,我将如何告诉EF在where子句中添加记录ID?

PS:此逻辑与SQL Server实体框架完美配合。我不确定为什么它不能在MySQL EF中使用。

我还跟踪存储库/当前dbcontext是否有任何更改,是否有任何更改且没有错误,我将启用“保存按钮/保存命令”。

0 个答案:

没有答案