当前位置: 首页 > 编程语言 > C#

DbContext已被释放导致操作无法完成分享

时间:2023-04-10 20:30:50 C#

DbContext已被释放导致操作无法完成数据库中央服务器)增删改查详细信息。在我的Controller类中,我写道:publicclassRegController:Controller{////GET:/Reg/privatestringCmdStr=ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;publicActionResultIndex(){使用(vardb=newRegModelContext(CmdStr)){returnView(db.Registrant);当我执行我的应用程序时,它在foreach语句的索引视图中给我一个错误:@modelIEnumerable@{Layout=null;}Index@Html.ActionLink("CreateNew","Create")UserNamePasswordEmailAddress@foreach(variteminModel){@Html.ActionLink("Edit","Edit",new{id=item.Id})|@Html.ActionLink("详情","详情",new{id=item.Id})|@Html.ActionLink("Delete","Delete",new{id=item.Id})@item.UserName@item.Password@item.Email@item.Address}错误是这样的:"Theoperationcouldnotbe已完成,因为DbContext已被释放。“你应该使用List作为模型传递我假设db.Registrant返回用户列表?如果是这样Listitems=null;using(vardb=newRegModelContext(CmdStr)){items=db.Registrant.ToList();}returnView(items);只是为了进一步评论,你需要分离你的关注点。你不应该像在控制器中那样使用数据库上下文。而是通过存储库或服务层使用它。我在使用问题时也遇到了这个问题。我删除了使用部分。修改下面的代码以适合您的场景。假设您要恢复用户列表。我会在我的存储库类中有这个:){returndbContext.Users;}}然后您可以通过Autofac、Ninject等将此存储库注入您的控制器。在您的控制器中,它看起来像这样:userRepository){this.userRepository=userRepository;}publicActionResultIndex(){UserViewModelviewModel=newUserViewModel{Users=userRepository.GetAll()};然后在您看来,您可以遍历用户。以上为C#学习教程:由于DbContext已经处理完毕,无法完成操作分享的所有内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处: