编辑内容时找不到实体类型

Posted

技术标签:

【中文标题】编辑内容时找不到实体类型【英文标题】:Entity type not found when editing contents 【发布时间】:2022-01-09 07:23:39 【问题描述】:

我有一个包含多个用户的模型。用户和项目之间的关系是多对多的。 EF Core 已自动生成第三个表来解决此问题。我试图允许用户编辑项目,编辑属性之一是删除用户。我希望能深入了解可能导致此错误的原因以及我应该如何处理 List 更改。我一直在通过在保存之前在值上放置EntityState.Modified 来处理编辑功能,到目前为止效果很好。提前致谢!

我一直遇到这个错误:

System.InvalidOperationException: The entity type 'List<ApplicationUser>' was not found. Ensure that the entity type has been added to the model.
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.GetOrCreateEntry(Object entity)
   at Microsoft.EntityFrameworkCore.DbContext.EntryWithoutDetectChanges[TEntity](TEntity entity)
   at Microsoft.EntityFrameworkCore.DbContext.Entry[TEntity](TEntity entity)
   at WebApp.Server.Controllers.ProjectsController.PutProject(Guid id, Project project) in C:\Users\Shahb\source\repos\WebApp\WebApp\Server\Controllers\ProjectsController.cs:line 78
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at WebApp.Server.Startup.<>c.<<Configure>b__5_0>d.MoveNext() in C:\Users\Shahb\source\repos\WebApp\WebApp\Server\Startup.cs:line 98
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events, IBackChannelLogoutService backChannelLogoutService)
   at IdentityServer4.Hosting.MutualTlsEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Builder.Extensions.MapMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

控制器中的以下行似乎出现了问题

_context.Entry(project.AssignedUsersToProject).State = EntityState.Modified;

这将使数据库知道对原始信息的修改

删除用户功能

    private void RemoveUser(string username) 

    var user = projectItem.AssignedUsersToProject.First(n => n.UserName.Equals(username));

    projectItem.AssignedUsersToProject.Remove(user);    

项目模型

 public class Project 
        [Key]
        public Guid ProjectId  get; set; 

        [Required]
        public string ProjectName  get; set;  

        public bool isComplete  get; set;  = false;

        public ICollection<ApplicationUser> AssignedUsersToProject  get; set; 
    

【问题讨论】:

【参考方案1】:

如果您使用的是 EF 正在跟踪的实体,则可以将其从列表中删除。

如果实体没有被跟踪并且您手动附加和设置 EntityState,那么当连接实体不在模型中时处理多对多是一个挑战。

https://docs.microsoft.com/en-us/answers/questions/251966/ef-core-5-many-to-many-disconected-addremove-witho.html

您收到错误的原因是您将 List 传递给 context.Entry。 EF 理解 ApplicationUser 但不理解 List。那是一种不同的“类型”。

【讨论】:

EF 在定义多对多关系时自动生成连接表。我是否必须通过此表并将用户从连接表中删除,然后才能正确地将其从列表中删除?

以上是关于编辑内容时找不到实体类型的主要内容,如果未能解决你的问题,请参考以下文章

找不到源类型的查询模式的实现:反序列化服务响应时找不到选择

运行 powershell -command 时找不到类型

在编译时找不到Spring数据存储库

S7200编程时找不到添加模似量模块设置

运行程序时找不到主类

jdbc.SQLServerException:将数据导出到 Azure SQL Server 时找不到数据类型“TEXT”