如何在没有App.config的情况下使用Entity Framework [英] How can l use Entity Framework without App.config

查看:124
本文介绍了如何在没有App.config的情况下使用Entity Framework的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想定义一个字符串变量,我想使用实体框架,而不需要 app.config 连接字符串在我的代码,并使用它连接到数据库。



请告诉我的方式,如果它是

解决方案

你没有提到你正在使用的方法(数据库优先,模型优先,代码优先) - 但是基本上,最终你需要定义一个字符串变量并赋予它一个有效的EF连接字符串

  string myConnectionString =...(在此定义有效的EF连接字符串)......; 

数据库优先方法示例:

  string myConnectionString = @metadata = .\Model1.csdl | .\Model1.ssdl | .\Model1.msl; provider = System.Data.SqlClient; provider connection string = ; data source =; initial catalog = test; integrated security = True; multipleactiveresultsets = True; App = EntityFramework; 

然后使用它创建您的 ObjectContext (数据库和模型优先)或 DbContext (代码优先)

  using(ObjectContext ctx = new ObjectContext(myConnectionString))
{
//你的EF魔法在这里.....
}

但坦白地说,我认为这是一个非常糟糕的主意,因为这使得不可能您将应用程序移动到另一台机器 - 没有人可以安装并运行它,因为连接字符串被硬编码到您的C#代码.....具有配置文件的全部要点,以便您可以更改/适应诸如连接字符串,使得它们不仅绑定到单个机器/位置,而且可以适应给定用户/客户的特定需求。


I want to use Entity Framework without app.config file.

I want to define a string variable Connection String in my code and use that to connect to the database.

Please show me the way if it is possible.

解决方案

You're not mentioning what approach you're using (database-first, model-first, code-first) - but basically, in the end, you need to define a string variable and assign it a valid EF connection string

string myConnectionString = "...(define a valid EF connection string here)......";

Example for database-first approach:

string myConnectionString = @"metadata=.\Model1.csdl|.\Model1.ssdl|.\Model1.msl;provider=System.Data.SqlClient;provider connection string="";data source=.;initial catalog=test;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""";

and then use that to create your ObjectContext (database- and model-first) or DbContext (code-first)

using(ObjectContext ctx = new ObjectContext(myConnectionString))
{
    // do your EF magic here.....
}

But quite honestly - I think this is a really bad idea since this makes it impossible for you to move your application to another machine - no one else can install and run this, since the connection string is hard-coded into your C# code..... the whole point of having config files is so that you can change / adapt things like connection strings so that they are not tied to a single machine/location but can be adapted to the particular needs of a given user / customer....

这篇关于如何在没有App.config的情况下使用Entity Framework的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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