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());
}

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
741 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,854 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,928 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Rijwan Ansari 746 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.