Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<T>' to 'T'

I am using ASP.NET core 2.2 for developing web apis. I have the following method in repository class:

public async Task<Articles> AddAsync(Articles article)
{
   return await _context.Articles.AddAsync(article);
}

I am getting the below error:

Cannot implicitly convert type 'Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<Author.Command.Persistence.DBContextAggregate.Articles>' to 'Author.Command.Persistence.DBContextAggregate.Articles'

Here I am trying to use the AddAsync version to save the data.

Can anyone help me to provide their guidance to fix this issue?

like image 988
santosh kumar patro Avatar asked Jul 24 '19 14:07

santosh kumar patro


1 Answers

The AddAsync method does not return just the provided type, in your case Articles. It does return Task<EntityEntry>. To fix your issue change your code to the following.

public async Task<Articles> AddAsync(Articles article)
{
   await _context.Articles.AddAsync(article);
   return article;
}

The changes made to the article instance will persist, since EFCore will track the provided Entity. See the MSDN for more information.

What will basically happen now is that your Articles instance is added to the DBSet of the DBContext. If the primary key is generated for you, it will actually set it in the instance you provided the AddAsync method.

EDIT

As Chris Pratt mentioned from the docs

This method is async only to allow special value generators, such as the one used by 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo', to access the database asynchronously. For all other cases the non async method should be used.

So you should instead use the synchronous versions Add instead.

So the code should look something like this.

public Articles Add(Articles article)
{
   _context.Articles.Add(article);
   return article;
}
like image 110
Twenty Avatar answered Sep 19 '22 20:09

Twenty