无法将类型 'Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<T>' 隐式转换为 'T'
Cannot implicitly convert type 'Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<T>' to 'T'
我正在使用 ASP.NET 核心 2.2 开发网络 API。我在存储库 class:
中有以下方法
public async Task<Articles> AddAsync(Articles article)
{
return await _context.Articles.AddAsync(article);
}
我收到以下错误:
Cannot implicitly convert type 'Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<Author.Command.Persistence.DBContextAggregate.Articles>' to 'Author.Command.Persistence.DBContextAggregate.Articles'
这里我尝试使用AddAsync版本来保存数据。
任何人都可以帮助我提供解决此问题的指导吗?
AddAsync
方法不只是 return 提供的类型,在您的情况下 Articles
。它确实 return Task<EntityEntry>
。要解决您的问题,请将您的代码更改为以下内容。
public async Task<Articles> AddAsync(Articles article)
{
await _context.Articles.AddAsync(article);
return article;
}
对文章实例所做的更改将持续存在,因为 EFCore 将跟踪提供的实体。
有关详细信息,请参阅 MSDN。
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.
编辑
正如文档中提到的 Chris Pratt
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.
因此您应该改用同步版本 Add
。
所以代码应该是这样的。
public Articles Add(Articles article)
{
_context.Articles.Add(article);
return article;
}
我正在使用 ASP.NET 核心 2.2 开发网络 API。我在存储库 class:
中有以下方法public async Task<Articles> AddAsync(Articles article)
{
return await _context.Articles.AddAsync(article);
}
我收到以下错误:
Cannot implicitly convert type 'Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<Author.Command.Persistence.DBContextAggregate.Articles>' to 'Author.Command.Persistence.DBContextAggregate.Articles'
这里我尝试使用AddAsync版本来保存数据。
任何人都可以帮助我提供解决此问题的指导吗?
AddAsync
方法不只是 return 提供的类型,在您的情况下 Articles
。它确实 return Task<EntityEntry>
。要解决您的问题,请将您的代码更改为以下内容。
public async Task<Articles> AddAsync(Articles article)
{
await _context.Articles.AddAsync(article);
return article;
}
对文章实例所做的更改将持续存在,因为 EFCore 将跟踪提供的实体。 有关详细信息,请参阅 MSDN。
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.
编辑
正如文档中提到的 Chris Pratt
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.
因此您应该改用同步版本 Add
。
所以代码应该是这样的。
public Articles Add(Articles article)
{
_context.Articles.Add(article);
return article;
}