0

Использую net core 3.1 + Entity framework core. Есть модель User и UserType, которую сохраняю в БД. К ним использую отдельные DTO для создания и чтения. В контроллер приходит Dto, маплю ее в модель юзер. Далее модель отправляю в бд, сохраняю. Потом в контроллере обратно маплю в Dto, и там Ид и юзер тип не обновленные, хотя все в базу сохранено. Отслеживание не отключал. Проблему в контроллере решил созданием новым экземпляров модели, но это неверно.

Как решить вопрос?

Модельки:

public class User
{
    [Key]
     public int Id { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 5)]
    public string Nickname { get; set; }

    [EmailAddress]
    public string Email { get; set; }

    [Phone]
    public string PhoneNumber { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 5)]
    public string Password { get; set; }

    public int UserTypeId { get; set; } 

    public virtual UserType UserType { get; set; }
} 

public class UserType
{
    [Key]
    public int Id { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 5)]
    public string Name { get; set; }
}

К ним DTO для создания

public class UserCreateDto
{
    [Required(AllowEmptyStrings = false, ErrorMessage = "Nickname not specified")]
    [StringLength(50, MinimumLength = 5)]
    public string Nickname { get; set; }

    [EmailAddress]
    public string Email { get; set; }

    [Phone]
    public string PhoneNumber { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "Password not specified")]
    [StringLength(50, MinimumLength = 5)]
    public string Password { get; set; }

    [Required(AllowEmptyStrings = false)]
    [Compare("Password", ErrorMessage = "Passwords don't match")]
    public string PasswordConfirm { get; set; }
}

public class UserTypeCreateDto
{
    [Required(AllowEmptyStrings = false, ErrorMessage = "User's type not specified")]
    [StringLength(50, MinimumLength = 3)]
    public string Name { get; set; }
}

и для чтения

public class UserReadDto
{
    public int Id { get; set; }
    public string Nickname { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public UserTypeReadDto UserType { get; set; }
}

public class UserTypeReadDto
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Реализация метода в репозитории юзера. Уже тут пришлось возвращать обновленный юзер. Иначе в контроллере после вызова этого метода данные не обновлялись. Отслеживание для EF Core не отключал, метод AsNoTracking() не вызываю.

public async Task<User> AddAsync(User user)
{
    var context = dbContextFactory.Create(typeof(UserRepository));

    var userTypeId = await context.UserTypes
                                  .Where(x => x.Name == "Client")
                                  .Select(x => x.Id)
                                  .FirstOrDefaultAsync();
    if (userTypeId == 0)
    {
        UserType userType = new UserType
        {
            Name = "Client"
        };

        await context.UserTypes.AddAsync(userType);
        await context.SaveChangesAsync();
 
        userTypeId = userType.Id;
    }

    User newUser = new User
    {
        Nickname = user.Nickname,
        Email = user.Email,
        PhoneNumber = user.PhoneNumber,
        Password = user.Password,
        UserTypeId = userTypeId
    };

    await context.Users.AddAsync(newUser);
    await context.SaveChangesAsync();

    return newUser;
}

И собственно контроллер.

[HttpPost("")]
public async Task<IActionResult> CreateUserAsync(UserCreateDto userDto)
{
    if (userDto == null || !ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var user = mapper.Map<User>(userDto);

    //after saving to the database(context.SaveChangesAsync()), the user model is not updated.
    //I was unable to fix this.So I do the following:
    
    var userResult = await userRepository.AddAsync(user); // get user with Id from database.

    userResult = await userRepository.GetByIdAsync(userResult.Id); // get user with userType from 
    database.

    var userReadDto = mapper.Map<UserReadDto>(userResult);

    return CreatedAtAction(nameof(GetUserByIdAsync), new { id = userReadDto.Id }, userReadDto);
}

2
  • Не совсем понятно. Добавьте в код комментарии, до какого места всё идёт нормально, а где ломается. 8 фев 2021 в 12:33
  • Зачем вызывается GetByIdAsync? Ведь userResult ещё до этого получен. 8 фев 2021 в 12:34

1 ответ 1

0

Подсказали то, что лежало на поверхности. Я в репозитории создавал новый экземпляр юзера вместо обновления существующего. В этом была вся проблема.

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.