HOW TO:实体框架的动态连接字符串

HOW TO: dynamic connection string for entity framework(HOW TO:实体框架的动态连接字符串)
本文介绍了HOW TO:实体框架的动态连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜欢标题.我该怎么做?

Like the title. How can I do it?

我尝试了一些东西,但它没有像我预期的那样工作.

I tried something, but it doesn't work like I was expecting.

我正在使用实体框架模型.我需要像参数一样传递我的连接字符串,所以,在另一个文件中,我已经写了

I'm using an Entity Framework model. I need to pass my connection string like parameter, so, in another file, I've written

namespace MyNamespace.Model
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class MyEntities: DbContext
    {
        public MyEntities(string nameOrConnectionString) : base(nameOrConnectionString)
        {

        }
    }
}

当我启动应用程序时,我以这种方式调用这个构造函数,所以我可以在应用程序中引用这个:

When I startup the app, I call this constructor in this way, so I can refer to this from anyway in the app:

public static MyEntities dbContext = new MyEntities(mdlImpostazioni.SetConnectionString());

其中 mdlImpostazioni.SetConnectionString() 返回一个字符串(数据正确):

where mdlImpostazioni.SetConnectionString() returns a string (the data are correct):

server=192.168.1.100SVILUPPO;database=MyDB;uid=myName;pwd=111111;

当我执行这段代码时,似乎一切正常,但是当我尝试进行如下查询时:

When I execute this code, it seems to be all ok, but when I try to make a query like:

var query = (from r in MainWindow.dbContext.TabTipoSistema select r);

它从这里抛出一个异常:

it throws an exception from here:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    throw new UnintentionalCodeFirstException(); //exception here
}

所以,这是一个不好的方法......哪个是正确的?(仅使用代码 C#,而不是来自 xaml)

So, this is a bad way... which is the right one? (using only code C#, not from xaml)

推荐答案

你的方法是正确的,但是你需要记住连接字​​符串EF需要元数据等等.所以使用EntityConnectionStringBuilder.例如:

Your approach is correct, but you need to remember the connection string for EF requires the metadata and so on. So use the EntityConnectionStringBuilder. For example:

// the model name in the app.config connection string (any model name - Model1?)
private static string GetConnectionString(string model, YourSettings settings)
{
    // Build the provider connection string with configurable settings
    var providerSB = new SqlConnectionStringBuilder
    {
        // You can also pass the sql connection string as a parameter instead of settings
        InitialCatalog = settings.InitialCatalog,
        DataSource = settings.DataSource,
        UserID = settings.User,
        Password = settings.Password
    };

    var efConnection = new EntityConnectionStringBuilder();
    // or the config file based connection without provider connection string
    // var efConnection = new EntityConnectionStringBuilder(@"metadata=res://*/model1.csdl|res://*/model1.ssdl|res://*/model1.msl;provider=System.Data.SqlClient;");
    efConnection.Provider = "System.Data.SqlClient";
    efConnection.ProviderConnectionString = providerSB.ConnectionString;
    // based on whether you choose to supply the app.config connection string to the constructor
    efConnection.Metadata = string.Format("res://*/Model.{0}.csdl|res://*/Model.{0}.ssdl|res://*/Model.{0}.msl", model); ;
    return efConnection.ToString();

}
// Or just pass the connection string
private static string GetConnectionString(string model, string providerConnectionString)
{

    var efConnection = new EntityConnectionStringBuilder();
    // or the config file based connection without provider connection string
    // var efConnection = new EntityConnectionStringBuilder(@"metadata=res://*/model1.csdl|res://*/model1.ssdl|res://*/model1.msl;provider=System.Data.SqlClient;");
    efConnection.Provider = "System.Data.SqlClient";
    efConnection.ProviderConnectionString = providerConnectionString;
    // based on whether you choose to supply the app.config connection string to the constructor
    efConnection.Metadata = string.Format("res://*/Model.{0}.csdl|res://*/Model.{0}.ssdl|res://*/Model.{0}.msl", model);
    // Make sure the "res://*/..." matches what's already in your config file.
    return efConnection.ToString();

}

编辑

您得到的异常是因为当您传递纯 SQL 连接字符串时,它假定您首先使用代码,因此它调用 OnModelCreation 事件.当您包含如上所示的 MetaData 部分时,它告诉 EF 它是一个完整的 EF 连接字符串.

The exception you get is because when you pass a pure SQL connection string, it assumes you are working with Code first, so it calls the OnModelCreation event. When you include the MetaData section as shown above, that tells EF it's a complete EF connection string.

这篇关于HOW TO:实体框架的动态连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)