SaveChangesAsync is not Working .Without SavechangesAsync Data inserted into Database

Walidulhasan Boniamin 1 Reputation point
2022-10-19T10:29:36.073+00:00

public async Task<Result<ReturnResult>> Handle(CreateDocumentTypeCommand request, CancellationToken cancellationToken)
{
var documentType = DocumentType.Create(request.Id,request.documentName,request.documentNamebn,request.documentSerial,request.categoryId,request.description);
await _dbCon.DocumentType.AddAsync(documentType, cancellationToken);
//await _dbCon.SaveChangesAsync(cancellationToken);
return Result.Ok(ReturnResult.Created());
}

Developer technologies | .NET | Entity Framework Core
Developer technologies | .NET | Other
Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. Rijwan Ansari 766 Reputation points MVP
    2022-10-19T11:39:38.267+00:00

    Hi @Walidulhasan Boniamin

    This happens if you are using the same dbcontext object into another functions and doing savechanges.
    If you want to limit the dbcontext scope inside the function then do by using as shown below.

    Example

    public async Task<Result<ReturnResult>> Handle(CreateDocumentTypeCommand request, CancellationToken cancellationToken)  
    {  
    var documentType = DocumentType.Create(request.Id,request.documentName,request.documentNamebn,request.documentSerial,request.categoryId,request.description);  
    using (var newContext = new YourContext())  
    {  
    await newContext.DocumentType.AddAsync(documentType, cancellationToken);  
    await newContext.SaveChangesAsync(cancellationToken);  
    }  
    return Result.Ok(ReturnResult.Created());  
    }  
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.