新手碰到Entityc entity frameworkk版本冲突,求教

What am I doing wrong? How do I troubleshoot this?
I have a solution that has multiple projects. It is an MVC .NET 4.5 web application.
When invoking one of the projects AFTER I start in debug mode, I am getting this error.
The project that is causing this error has the following references:
They are both versions 6.0.0.0
Server Error in '/' Application.
Could not load file or assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileLoadException: Could not load file or assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x)
Source Error:
public vvvRepository() {
this._vvvEntities = new vvvEntities();
public vvvRepository(int commandTimeout) {
Source File: c:\tfs\PACE\eee Framework\branches\1.23\eeeService\Adapters\vvv\eeeService.vvv.DataAccess\vvvRepository.cs
Assembly Load Trace: The following information can be helpful to determine why the assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c' could not be loaded.
=== Pre-bind state information ===
LOG: User = eee\ksmith
LOG: DisplayName = EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c
(Fully-specified)
LOG: Appbase = file:///C:/tfs/PACE/eee Framework/branches/1.23/eeeService/vvvWebProd/zzz/zzz/
LOG: Initial PrivatePath = C:\tfs\PACE\eee Framework\branches\1.23\eeeService\vvvWebProd\zzz\zzz\bin
Calling assembly : eeeService.vvv.DataAccess, Version=1.22.0.0, Culture=neutral, PublicKeyToken=null.
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\tfs\PACE\eee Framework\branches\1.23\eeeService\vvvWebProd\zzz\zzz\web.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c
LOG: Attempting download of new URL file:///C:/Users/ksmith/AppData/Local/Temp/Temporary ASP.NET Files/root/fe9ab6/EntityFramework.DLL.
LOG: Attempting download of new URL file:///C:/Users/ksmith/AppData/Local/Temp/Temporary ASP.NET Files/root/fe9ab6/EntityFramework/EntityFramework.DLL.
LOG: Attempting download of new URL file:///C:/tfs/PACE/eee Framework/branches/1.23/eeeService/vvvWebProd/zzz/zzz/bin/EntityFramework.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Major Version
ERR: Failed to complete setup of assembly (hr = 0x). Probing terminated.
Stack Trace:
[FileLoadException: Could not load file or assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x)]
eeeService.vvv.DataAccess.vvvRepository..ctor() in c:\tfs\PACE\eee Framework\branches\1.23\eeeService\Adapters\vvv\eeeService.vvv.DataAccess\vvvRepository.cs:141
ttt.ttt.get_Repository() in c:\tfs\PACE\eee Framework\branches\1.23\eeeService\vvvWebProd\zzz\ttt\ttt.cs:21
ttt.ttt.GetDeviceBySerialNumber(String serialNumber) in c:\tfs\PACE\eee Framework\branches\1.23\eeeService\vvvWebProd\zzz\ttt\ttt.cs:52
eee.EnterpriseServices.eeeFramework.zzz.Controllers.SettingsController.lookupDeviceForSettingsPost(String serialnumber) in c:\tfs\PACE\eee Framework\branches\1.23\eeeService\vvvWebProd\zzz\zzz\Controllers\SettingsController.cs:364
lambda_method(Closure , ControllerBase , Object[] ) +180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +435
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +50
System.Web.Mvc.Async.&&c__DisplayClass42.&BeginInvokeSynchronousActionMethod&b__41() +75
System.Web.Mvc.Async.&&c__DisplayClass8`1.&BeginSynchronous&b__7(IAsyncResult _) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +73
System.Web.Mvc.Async.&&c__DisplayClass39.&BeginInvokeActionMethodWithFilters&b__33() +126
System.Web.Mvc.Async.&&c__DisplayClass4f.&InvokeActionMethodFilterAsynchronously&b__49() +323
System.Web.Mvc.Async.&&c__DisplayClass37.&BeginInvokeActionMethodWithFilters&b__36(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +74
System.Web.Mvc.Async.&&c__DisplayClass2a.&BeginInvokeAction&b__20() +68
System.Web.Mvc.Async.&&c__DisplayClass25.&BeginInvokeAction&b__22(IAsyncResult asyncResult) +184
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +66
System.Web.Mvc.&&c__DisplayClass1d.&BeginExecuteCore&b__18(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.&&c__DisplayClass4.&MakeVoidDelegate&b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +68
System.Web.Mvc.Async.&&c__DisplayClass4.&MakeVoidDelegate&b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +65
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.&&c__DisplayClass8.&BeginProcessRequest&b__3(IAsyncResult asyncResult) +45
System.Web.Mvc.Async.&&c__DisplayClass4.&MakeVoidDelegate&b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +66
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9628700
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.
Here is the app.config file of the project throwing the exception:
&?xml version="1.0" encoding="utf-8"?&
&configuration&
&configSections&
&section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b" requirePermission="false" /&
&section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b" requirePermission="false" /&
&!-- For more information on Entity Framework configuration, visit /fwlink/?LinkID=237468 --&
&!-- For more information on Entity Framework configuration, visit /fwlink/?LinkID=237468 --&
&section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b" requirePermission="false" /&
&/configSections&
&connectionStrings&
&entityFramework&
&defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"&
&parameters&
&parameter value="v11.0" /&
&/parameters&
&/defaultConnectionFactory&
&providers&
&provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /&
&/providers&
&/entityFramework&
&supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /&
&/startup&
&entityFramework&
&defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /&
&/entityFramework&
&assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&
&dependentAssembly&
&assemblyIdentity name="EntityFramework" publicKeyToken="31bf" /&
&bindingRedirect oldVersion="0.0.0.0-6.0.1.0" newVersion="6.0.0.0" /&
&/dependentAssembly&
&/assemblyBinding&
&/runtime&
&system.serviceModel&
&bindings&
&wsHttpBinding&
&/wsHttpBinding&
&/bindings&
&/system.serviceModel&&/configuration&
What am I doing wrong? How do I troubleshoot this?
解决方案 The Main project probably has a reference to a older version of Entity Framework and thus the older dll is in the build. Make sure that all projects that are using the problematic project have the new reference
本文地址: &
我在做什么错了?我该如何解决呢? 我有一个具有多个项目的解决方案。这是一个MVC .NET 4.5的Web应用程序。 在调用的项目之一后,我在调试模式下启动,我收到此错误。 这是造成此错误的项目有以下参考资料:
他们是两个版本的 6.0.0.0
在'/'应用程序的服务器错误。
无法加载文件或程序集“的EntityFramework,版本6.0.0.0 =文化=中性公钥= b77a5c”或它的一个依赖。找到的程序集清单定义不匹配程序集引用。 (异常来自HRESULT:0x)
说明:执行当前Web请求的执行过程中发生未处理的异常。请检查堆栈跟踪有关该错误的详细信息以及它起源于code。 异常详细信息:System.IO.FileLoadException:无法加载文件或程序集“的EntityFramework,版本6.0.0.0 =文化=中性公钥= b77a5c”或它的一个依赖。找到的程序集清单定义不匹配程序集引用。 (异常来自HRESULT:0x)源错误:139线:公共vvvRepository(){140线:this._vvvEntities =新vvvEntities();141线:}142线:143线:公共vvvRepository(INT的CommandTimeout){源文件:C:\\ TFS \\ PACE \\ EEE框架\\分支机构\\ 1.23 \\ eeeService \\适配器\\ VVV \\ eeeService.vvv.DataAccess \\ vvvRepository.cs线:141程序集加载跟踪:下列信息有助于确定程序集“的EntityFramework,版本6.0.0.0 =文化=中性公钥= b77a5c'无法加载。=== pre-绑定状态信息===LOG:用户= EEE \\ ksmith日志:显示名称=的EntityFramework,版本6.0.0.0 =文化=中性公钥= b77a5c (完全指定)日志:应用平台=文件:/// C:/ TFS / PACE / EEE框架/分支机构/ 1.23 / eeeService / vvvWebProd / ZZZ / ZZZ /LOG:初始PrivatePath = C:\\ TFS \\ PACE \\ EEE框架\\分支机构\\ 1.23 \\ eeeService \\ vvvWebProd \\ ZZZ \\ ZZZ \\ BIN调用汇编:eeeService.vvv.DataAccess,版本= 1.22.0.0,文化=中立,公钥=空。===日志:此绑定的默认加载上下文开始。日志:正在使用应用程序配置文件:C:\\ TFS \\ PACE \\ EEE框架\\分支机构\\ 1.23 \\ eeeService \\ vvvWebProd \\ ZZZ \\ ZZZ \\ web.config中日志:使用主机配置文件:日志:从C使用计算机配置文件:\\ WINDOWS \\ Microsoft.NET \\框架\\ v4.0.30319 \\ CONFIG \\ machine.config中。日志:后政策参考:的EntityFramework,版本6.0.0.0 =文化=中性公钥= b77a5c日志:新的URL文件试图下载:/// C:/用户/ ksmith /应用程序数据/本地/温度/ ASP.NET临时文件/根/
/ 49fe9ab6 / EntityFramework.DLL。日志:新的URL文件试图下载:/// C:/用户/ ksmith /应用程序数据/本地/温度/ ASP.NET临时文件/根/
/ 49fe9ab6 /的EntityFramework / EntityFramework.DLL。日志:新的URL文件试图下载:/// C:/ TFS / PACE / EEE框架/分支机构/ 1.23 / eeeService / vvvWebProd / ZZZ / ZZZ /斌/ EntityFramework.DLL。警告:比较程序集名称时发生不匹配:主版本错误:未能完成组装(HR = 0x)的设置。探测终止。堆栈跟踪:[FileLoadException:未能加载文件或程序集“的EntityFramework,版本6.0.0.0 =文化=中性公钥= b77a5c”或它的一个依赖。找到的程序集清单定义不匹配程序集引用。 (异常来自HRESULT:0x)]
eeeService.vvv.DataAccess.vvvRepository..ctor()在C:\\ TFS \\ PACE \\ EEE框架\\分支机构\\ 1.23 \\ eeeService \\适配器\\ VVV \\ eeeService.vvv.DataAccess \\ vvvRepository.cs:141
ttt.ttt.get_Repository()在C:\\ TFS \\ PACE \\ EEE框架\\分支机构\\ 1.23 \\ eeeService \\ vvvWebProd \\ ZZZ \\ TTT \\ ttt.cs:21
ttt.ttt.GetDeviceBySerialNumber(字符串的serialNumber)在C:\\ TFS \\ PACE \\ EEE框架\\分支机构\\ 1.23 \\ eeeService \\ vvvWebProd \\ ZZZ \\ TTT \\ ttt.cs:52
eee.EnterpriseServices.eeeFramework.zzz.Controllers.SettingsController.lookupDeviceForSettingsPost(String SERIALNUMBER)在C:\\ TFS \\ PACE \\ EEE框架\\分支机构\\ 1.23 \\ eeeService \\ vvvWebProd \\ ZZZ \\ ZZZ \\ \\控制器SettingsController.cs:364
lambda_method(封闭,ControllerBase,对象[])180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase控制器,对象[]参数)+59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext,IDictionary`2参数)435
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext,ActionDescriptor actionDescriptor,IDictionary`2参数)+60
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext,ActionDescriptor actionDescriptor,IDictionary`2参数)+50
System.Web.Mvc.Async<> c__DisplayClass42< BeginInvokeSynchronousActionMethod> b__41()+75
System.Web.Mvc.Async<> c__DisplayClass8`1< BeginSynchronous> b__7(IAsyncResult的_)+44
System.Web.Mvc.Async.WrappedAsyncResult`1.End()+139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult的asyncResult,对象标记)+102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult的asyncResult)+73
System.Web.Mvc.Async<方式&&c__DisplayClass39 LT; BeginInvokeActionMethodWithFilters> b__33()+126
System.Web.Mvc.Async<方式&&c__DisplayClass4f LT; InvokeActionMethodFilterAsynchronously> b__49()323
System.Web.Mvc.Async.&&c__DisplayClass37.&BeginInvokeActionMethodWithFilters&b__36(IAsyncResult asyncResult)+44
System.Web.Mvc.Async.WrappedAsyncResult`1.End()+139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult的asyncResult,对象标记)+102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult的asyncResult)+74
System.Web.Mvc.Async<> c__DisplayClass2a< BeginInvokeAction> b__20()+68
System.Web.Mvc.Async<方式&&c__DisplayClass25 LT; BeginInvokeAction> b__22(IAsyncResult的asyncResult)184
System.Web.Mvc.Async.WrappedAsyncResult`1.End()+136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult的asyncResult,对象标记)+56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult的asyncResult)+66
System.Web.Mvc<> c__DisplayClass1d< BeginExecuteCore> b__18(IAsyncResult的asyncResult)+ 40
System.Web.Mvc.Async<方式&&c__DisplayClass4 LT; MakeVoidDelegate> b__3(IAsyncResult的AR)+47
System.Web.Mvc.Async.WrappedAsyncResult`1.End()+151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult的asyncResult,对象标记)+59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult的asyncResult,对象标记)+ 40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult的asyncResult)+68
System.Web.Mvc.Async<方式&&c__DisplayClass4 LT; MakeVoidDelegate> b__3(IAsyncResult的AR)+47
System.Web.Mvc.Async.WrappedAsyncResult`1.End()+151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult的asyncResult,对象标记)+59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult的asyncResult,对象标记)+ 40
System.Web.Mvc.Controller.EndExecute(IAsyncResult的asyncResult)+65
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult的asyncResult)+39
System.Web.Mvc<> c__DisplayClass8< BeginProcessRequest> b__3(IAsyncResult的asyncResult)+45
System.Web.Mvc.Async<方式&&c__DisplayClass4 LT; MakeVoidDelegate> b__3(IAsyncResult的AR)+47
System.Web.Mvc.Async.WrappedAsyncResult`1.End()+151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult的asyncResult,对象标记)+59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult的asyncResult,对象标记)+ 40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult的asyncResult)+66
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult的结果)+38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()9628700
System.Web.HttpApplication.ExecuteStep(IExecutionStep一步,布尔和放大器; completedSynchronously)+155版本信息:Microsoft .NET Framework版本:4.0.30319; ASP.NET版本:4.0. 下面是该项目引发异常的app.config文件: <?XML版本=“1.0”编码=“UTF-8”&GT?;<结构&
< configSections>
&节名称=“的EntityFramework”TYPE =“System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,的EntityFramework,版本6.0.0.0 =文化=中性公钥= b”requirePermission =“FALSE”/>
&节名称=“的EntityFramework”TYPE =“System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,的EntityFramework,版本= 4.4.0.0,文化=中性公钥= b”requirePermission =“FALSE”/>
<! - 有关Entity Framework的配置的详细信息,请访问/fwlink/?LinkID=237468
<! - 有关Entity Framework的配置的详细信息,请访问/fwlink/?LinkID=237468
&节名称=“的EntityFramework”TYPE =“System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,的EntityFramework,版本6.0.0.0 =文化=中性公钥= b”requirePermission =“FALSE”/>
< / configSections>
<&是connectionStrings GT;
<&的EntityFramework GT;
< defaultConnectionFactory TYPE =“System.Data.Entity.Infrastructure.LocalDbConnectionFactory,的EntityFramework”>
<&参数GT;
<参数值=“11.0”/>
< /参数>
< / defaultConnectionFactory>
<供应商>
<供应商invariantName =“System.Data.SqlClient的”TYPE =“System.Data.Entity.SqlServer.SqlProviderServices,EntityFramework.SqlServer”/>
< /供应商>
< /&的EntityFramework GT;
<&启动GT;
< supportedRuntime版本=“V4.0”SKU =“.net框架,版本= V4.5”/>
< /启动>
<&的EntityFramework GT;
< defaultConnectionFactory TYPE =“System.Data.Entity.Infrastructure.SqlConnectionFactory,的EntityFramework”/>
< /&的EntityFramework GT;
<&运行GT;
< assemblyBinding的xmlns =“瓮:架构 - 微软COM:asm.v1”>
< dependentAssembly>
< assemblyIdentity名称=“的EntityFramework”公钥=“31bf”/>
< bindingRedirect oldVersion =“0.0.0.0-6.0.1.0”NEWVERSION =“6.0.0.0”/>
< / dependentAssembly>
< / assemblyBinding>
< /运行>< system.serviceModel>
<&绑定GT;
<&的wsHttpBinding GT;
< /&的wsHttpBinding GT;
< /绑定>
< /system.serviceModel&< /结构&
我在做什么错了?我该如何解决呢? 解决方案 主要的项目可能有一个旧版本的实体框架,因此旧的DLL是在构建一个参考。请确保使用有问题的项目所有项目都有新的参考
本文地址: &
扫一扫关注官方微信[Entity Framework] Entityframework的简单应用 | IT知识库
-& 正文阅读
[Entity Framework]Entityframework的简单应用
Entityframework的简单应用
项目中使用EntityFramework&&项目代码:/cKAw3sSJWQwUX &提取码 871c文笔不好,技术也差。来这就是来提高自己的,欢迎批评。最后还留下一个小问题,如果你知道的话可以告诉我,谢谢。(邮箱:jin_)前言 11.&建立解决方案项目结构 12.&导入EntityFramework类库 13.&编写实体类 14.&编辑连接字符串 35.&编写BaseBLL类 36.&编写业务处理超类 47.&编写业务处理类 68.&应用 69.&疑难杂症 7&&前言数据库的使用在软件编程中占有很大的一个比例。尤其是在管理系统中,基本上没有哪个系统能离开数据库而单独存在。在编写数据库访问程序时最让人头疼的就是拼SQL,一般都需要在数据库和VS里颠倒好多次才能写出我们想要的那个语句。ORM的出现很好的解决了这个问题,它可以把SQL相关程序的编写变成类似强类型的语句,方便编写和调试,大大提高了工作效率。下面就把我在项目中如何使用EntiryFramework做一下简单的记录。开发环境:VS2010,SQLServer208,EntityFramework61.&建立解决方案项目结构EntityFramework是用来访问数据库的,根工程的类型没有关系,我们可以把它用用C/S的工程当中,也可以把它用到&B/S的工程当中。为了展示EntityFramework的使用方法,我们首先得建立一个例子解决方案。这个解决方案的最基础的普通三层结构,因为数据的访问主要靠EntityFramework来实现,所以数据访问层的实现基本看不出来了,使得整个解决方案好像就是个两层的一样。下面我们通过表格的形式来说明一下这个解决方案中各个工程的类型和做用。工程名层次类型作用是否引入EFJZAPP展示层应用程序应用程序否BLL业务逻辑层类库逻辑运算,数据访问是Model实体类类库数据库表到类的映射是2.&导入EntityFramework类库用Nuget把最新版本的EntityFramework导入到BLL,Model两个项目中。3.&编写实体类下面我们以下面图中这个实体类做为样本,来了解一下EntityFramework中的实体类如何定义。实体类是数据库表的映射,所以这个类的名称,属性名称,属性类型都是根我们设计的表有关联了。具体数据库中的类型映射为C#中的什么类型没有做过详细的研究,大概用过的总结如下,如果以后还会用到其他的,还会添加到这里来的。SqlServer中的类型C#中的类型Varchar(N)stringbitbooldatetimeDateTimeintinteger数据库定义如下:
根据表格,我们可以把上面的数据库表写为如下实体类,实体类统一放到Model工程里:
using ponentModel.DataAnnotations.S
using ponentModel.DataA
namespace Model
[Table("User")]
public class UserDefinition
/// &summary&
/// 用?户&id
/// &/summary&
[Key,DatabaseGenerated(DatabaseGeneratedOption.None)]
public string UserId { set; get; }
public string LoginName { set; get; }
public string Name { set; get; }
public string Password { set; get; }
public bool Sex { set; get; }
public string DeptId { set; get; }
public DateTime CreateDate { set; get; }
public int Status { set; get; }
public string SizeId { get; set; }
public bool Visible { get; set; }
}View Code&[Table("User")]:定义UserDefinition对应的数据库表为User
&[Key]:定义UserId&为主键
&[DatabaseGenerated(DatabaseGeneratedOption.None)]:定义字段的数据生成项;DatabaseGeneratedOption有三个值;Identity:自增长;None:不处理;Computed:计算列。
4.&编辑连接字符串连接字符串放在JZAPP工程的配置文件里(app.config),如果工程中有这个文件那就直接使用,如果没有就新建一个。在配置文件里添加一个connectionStrings节。它是configuration的子节点。
&?xml version="1.0" encoding="utf-8"?&
&configuration&
&connectionStrings&
&add name="ABC"
connectionString="Data Source=127.0.0.1;Initial Catalog=Persist Security Info=TUser ID=Password=landmark"
providerName="System.Data.SqlClient" /&
&/connectionStrings&
&/configuration&View Code&Name:本连接字符串的名称,它在本程序中用于BaseBLL类的构造函数中
&Data&Source:数据库服务器的名称,也可以是IP,URL
&Initial&Catalog:数据库的名称贷
&User&ID:数据库的用户名
&Password:数据库密码
5.&编写BaseBLL类这个类是访问数据库的基础,有了这个类才可以写其他的业务处理。如果没有业务处理,可以直接用这个类操作数据库。它必须继承自DbContext。
using System.Data.E
using System.Data.Entity.SqlS
namespace BLL
public class BaseBLL:DbContext
public DbSet&UserDefinition& User { get; set; }
public BaseBLL()
: base("abc")
}View Code编写这个类要注意三点:&BaseBLL必须继承自DbContext
&用DbSet&&类型实例化每一个实体类
&在构造函数中赋值连接字符串的名称6.&编写业务处理超类我们可以针对不同的业务来编写代码,在程序开发中,遇到重复性太强的地方,把它总结一下,写出了以下几个常函数,把它们定义成了一个父类:
public class ParentBLL&T& where T : class
public virtual void Add(T p)
using (BaseBLL bll = new BaseBLL())
bll.Set&T&().Add(p);
bll.SaveChanges();
public T Find(object p)
using (BaseBLL bll = new BaseBLL())
return bll.Set&T&().Find(p);
public IList&T& Query()
using (BaseBLL bll = new BaseBLL())
return (from o in bll.Set&T&() select o).ToList();
public virtual void Remove(T p)
using (BaseBLL bll = new BaseBLL())
bll.Set&T&().Attach(p);
bll.Set&T&().Remove(p);
bll.SaveChanges();
public virtual void Update(T p)
using (BaseBLL bll = new BaseBLL())
bll.Entry(p).State = EntityState.M
bll.SaveChanges();
}View Code7.&编写业务处理类业务处理类一开始应该是非常简单的,我们直接用业务处理类的父类来实现它就我们开始的使用了。
using System.Data.Entity.SqlS
namespace BLL
public class UserBLL : ParentBLL&UserDefinition&
}View Code8.&建库SQL
create table "User" (
varchar(100)
varchar(100)
varchar(100)
varchar(100)
varchar(100)
CreateDate
varchar(100)
constraint PK_USER primary key (UserId)
GoView Code9.&应用下面的程序中用上面的框架写的一个添加数据程序。
private void button1_Click(object sender, EventArgs e)
var bll = new UserBLL();
var p = new UserDefinition();
p.UserId = Guid.NewGuid().ToString();
p.Name = Guid.NewGuid().ToString();
p.SizeId = Guid.NewGuid().ToString();
p.CreateDate = DateTime.N
bll.Add(p);
}View Code10.&疑难杂症写到这里关于EF的应用就算是已经说完了。凭借上面的代码,我们已经可以用EF来访问数据库了。如果这里面还有一人雷。如果把上面的代码直接复制到工程里去执行可能做引发一个很莫名其妙的错误,那就是EF的一个程序集没有输出到JZAPP的输出目录里面。EF6在安装到项目时在项目里添加了两个程序集分别为EntityFramework和EntityFramework.Sqlserver.我们的解决方案里。Model和BLL工程引用了EntityFramework和EntityFramework.Sqlserver;JZAPP又引用了&Model和BLL。JZAPP没有直接引用EntityFramework和EntityFramework.Sqlserver。编译解决方案后,Model和BLL工程的输出目录里有EntityFramework和EntityFramework.Sqlserver程序集。JZAPP工程的输出目录里只有EntityFramework一个程序集。工程可以编译通过,但是运行就会出错误,这个问题刚开始很让我莫名其妙。后来经过哥儿们的帮忙看到一个博客。里面有一句话(间接引用程序集,如果只是引用而没有调用,程序集不会被输出到目标目录)让我知道了原因。经过测试这句话是正确的。解决方法就是在程序中调用一下这个程序集里的程序。如下:
using System.Data.Entity.SqlS
namespace BLL
public class UserBLL : ParentBLL&UserDefinition&
private string UserName()
using (var bll = new BaseBLL())
return SqlFunctions.UserName();
}View Code随便找一个地方写一个没用的函数就可以了。经过测试这个方法编译可以通过,也能解决上面的问题。但是调用会出错。没关系了,解决问题就好了。SqlFunctions类具体怎么用以后再研究吧。好像还有其他更好的方法来解决这个问题,如果你知道,请告诉我,谢谢。
加: 14:05:10&
更: 14:06:24&
&&网站联系: qq: email:&

我要回帖

更多关于 entityframework core 的文章

 

随机推荐