如何使用 EF4 作为 DAL
我目前正在我的 ASP.NET 网站中使用 EF 4 来访问 MySql 数据库。这很好用。但是我现在想要另一个网站项目访问相同的实体。我该如何设置?
我不能只引用原始网站,因为它是一个网站,而不是一个网络应用程序。所以想必,我需要将实体数据模型放在自己的项目中并编译为 DLL。但是...
- 哪种项目类型?
- 我是否只需剪切并粘贴 DataModel.edmx 和 DataModel.Designer.cs,在两个网站中编译并添加引用?那么命名空间呢?
- 连接字符串应该放在哪里?目前它位于我项目的 Web.config 中。
我真的不知道从哪里开始 - 到目前为止我只是按照教程来让 EF 正常工作!如果有人有时间的话,我真的很感激分步说明。谢谢。
I am currently using EF 4 with my ASP.NET Website to access a MySql database. This works fine. However I now want another Web Site project to access the same entities. How do I set this up?
I can't just reference the original website as it's a Web Site, not a Web Application. So presumably, I need to put the Entity Data Model in its own project and compile to a DLL. But...
- Which project type?
- Do I just cut and paste the DataModel.edmx and DataModel.Designer.cs, compile and add a reference in both websites? What about namespaces?
- Where do I put the connection string? At the moment it's in my project's Web.config.
I really have no idea where to begin - I've just followed tutorials to get EF working up to now! I'd really appreciate step-by-step instructions if anyone has time. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该模型应放置在新的类库项目中。我的偏好是基于现有模型重新创建模型。对于命名空间,我喜欢使用 {CompanyName}.DataAccess。从网站项目中删除旧模型,添加对新类库项目的引用并构建网站项目。该网站项目将在很多地方中断,但将命名空间更改为新的数据访问程序集应该是一个简单的问题。我更喜欢这种方法来剪切/粘贴,因为现在你有了干净的命名空间。请小心任何可能包含带有实体名称的字符串的地方,例如您使用 Include 时(如果您使用 EF 4 和延迟加载,这应该不是问题)。将两个网站项目的连接字符串保留在 web.config 中。当您在类库中创建模型时,它会在 app.config 中添加一个连接字符串。没关系,它就在那里,以便模型知道在刷新数据库时如何连接到数据库。
The model should be placed in a new class library project. My preference would be to recreate the model at this point based on the existing model. For the namespace I like to use {CompanyName}.DataAccess. Remove the old model from your web site project, add a reference to the new class library project and build the web site project. The website project will break in many places, but it should be a simple matter of changing the namespace to the new data access assembly. I prefer this method as to cut/paste because now you have nice clean namespaces. Be careful of any places you may have strings with entity names in them, like if you were using Include (if you are using EF 4 and lazy loading, this should not be a problem). Leave the connection string in web.config for both of the web site projects. When you create the model in the class library, it will add a connection string in app.config. That is OK, it is just there so the model knows how to connect to the database when you refresh it.