放置Database.SetInitializer [英] Place to put Database.SetInitializer

查看:105
本文介绍了放置Database.SetInitializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个项目,最终可以使用多个UI版本/变体,但到目前为止,我的解决方案Web中有两个子项目 - 包含ASP.NET MVC的Web界面。服务项目是我有数据库上下文和模型定义的地方。



我的目标是在我的Web项目中对EF特定代码进行最少或可能没有引用。我希望它是独立的,所以当我用服务后端切换dll(从让我们说SQL到XML或MySQL)我不应该在我的MVC项目中进行多个修改。



这是它的外观:





我的问题是:
- 到目前为止,我没有发现使用数据库的例子。 SetInitializer位于Global.asax之外。如果我的工厂类型的DatabaseContextProvider类或服务类中的模型发生变化,我想将数据库重新创建,从上下文中提取数据,并将其提供给具有DTO的UI。这个位置有什么缺点吗?
- 我想使上下文的connectionString可以使用Properties / Settings.settings文件进行配置 - 是否合理?

解决方案

在第一次使用 DbContext 之前,您将需要一种调用 Database.SetInitializer 方法的机制。这就是为什么它通常在 Global.asax 文件中调用。



您可以使用初始化方法创建一个类在 tm.Service 项目中,并在 Application_Start 方法中调用它,并放入数据库。 SetInitializer 在该初始化方法中。



它可以从设置文件提供连接字符串。


I'm working on a project that at can end up with multiple UI versions / variants, but so far I've got two subprojects in my solution Web - containing Web interface with ASP.NET MVC. Service project is place where I have my database context and models defined.

My Goal is to have minimum or possibly no references to EF specific code in my Web project. I want it to be independent so when I switch the dlls with service backend ( from let say SQL to XML or MySQL ) I shouldn't make multiple modifications in my MVC project.

This is how it looks :

My Questions are: - so far I've found no example of using Database.SetInitializer in other place than Global.asax. I'd like to put database re-creation if model changed in my factory-like DatabaseContextProvider class or in service class that pulls out data from context and provides it to the UI with DTOs. Are there any cons of that location ? - I would like to have the context's connectionString to be configurable with Properties/Settings.settings file - is that reasonable ?

解决方案

You would need a mechanism to call the Database.SetInitializer method before the very first usage of the DbContext. That is why its usually called in the Global.asax file.

You can create a class with an initialization method in your tm.Service project and call it in the Application_Start method and put the Database.SetInitializer in that initialization method.

Its OK to supply the connection string from a setting file.

这篇关于放置Database.SetInitializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆