0

I want to Save User Information In the Database.

public async Task<User> CreateAsync(CreateRequestViewModel user)
    {
        User NewUser = new User
        {
            UserId = Guid.NewGuid(),
            Password = user.Password,
            UserName = user.UserName,
        };

        var resultUser = await _ProjectContext.Users.AddAsync(NewUser);


        Person person = new Person()
        {
            UserId = resultUser.Entity.UserId,
            RegisterDate = DateTime.Now,
            Email = user.Email,
            Gender = user.Gender,
            PersonId = Guid.NewGuid(),

        };
        await _ProjectContext.Persons.AddAsync(person);
        return resultUser.Entity;
    }

User Service Code:

public async Task<User> Create(CreateRequestViewModel user)
        {
            try
            {
                var model = await _unitOfWork.Users.CreateAsync(user);
                await _unitOfWork.CommitAsync();
                return model;
            }
            catch (Exception me)
            {

                throw;
            }

        }

but when to run this code:

 await _unitOfWork.CommitAsync();

code in CommitAsync:

 public async Task<int> CommitAsync()
    {
        int oo = 0;
        try
        {
            oo = await _context.SaveChangesAsync();
        }
        catch (Exception me)
        {

            throw;
        }
        return oo;
    }

I get this error:

Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'ProjectContext'.

How it can be fixed.

MrJahanbin
  • 243
  • 1
  • 2
  • 20
  • You have not used the provided Create function in User Service in your code. If it's possible please provide more clarification on how you are using the repository pattern. The problem indicates the dispose of the object: can this question be helpful? : https://stackoverflow.com/questions/6993407/cannot-access-a-disposed-object – Masoud Tahmasebi Jun 09 '20 at 06:13
  • Does this answer your question? [Cannot access a disposed object in ASP.NET Core when injecting DbContext](https://stackoverflow.com/questions/38704025/cannot-access-a-disposed-object-in-asp-net-core-when-injecting-dbcontext) – Masoud Tahmasebi Jun 09 '20 at 06:15

0 Answers0