How to track identity changes in EF Core?

c# entity-framework-core

Question

I have a service in my application which creates a User, and saves it to the database. Here's a method of my service:

    public async Task<UserDTO> CreateUserAsync(User newUser)
    {

        var result = (UserDTO)await _userRepository.CreateUserAsync(newUser);

        if (result != null)
        {

            await _userRepository.SaveChangesAsync();

        }

        return result;

    }

And a method from a UserRepository:

public async Task<User> CreateUserAsync(User newUser) => (await _dbContext.AddAsync(newUser)).Entity;

Here's a User class:

public class User
{

    public int UserId { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }

}

The problem is when the user is being added via service, UserId is not known yet. It has default value 0, then ef core saves it to a database, finding a proper UserId. But value returned by my methods has no UserId updated - it is still 0, and i would like to return updated value. How to achieve that in a proper way?

1
0
3/9/2020 11:43:51 AM

Popular Answer

newUser WILL have an Id read from the database.

Your code is casting from User to UserDTO, which is unlikely to work.

1
3/9/2020 11:57:43 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow