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

asp.net-core-2.2 c# entity-framework-core

Question

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?

1
2
7/24/2019 3:30:34 PM

Accepted Answer

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

Blockquotehis 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;
}
5
7/26/2019 7:33:29 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