简体   繁体   English

在配置中更改实体框架提供程序

[英]Change Entity Framework provider in configuration

I was hoping to be able to switch data providers to/from SQL Server and SQL Server Compact Edition via just a configuration change. 我希望能够通过配置更改将数据提供程序切换到SQL Server和SQL Server Compact Edition。 But it doesnt work and looking at the EDMX file I think I can see why: 但它不起作用,看着EDMX文件,我想我可以看到原因:

<edmx:StorageModels>
<Schema ... Provider="System.Data.SqlClient" ...

Is there any way to specify the provider in app.config or at runtime? 有没有办法在app.config或运行时指定提供程序?

The Storage-Model is tied to a specific provider, which will cause the Entity Framework to reject any DbConnection implementations that are not compatible with the specified provider. 存储模型与特定提供程序绑定,这将导致实体框架拒绝任何与指定提供程序不兼容的DbConnection实现。

If you look at an Entity Framework connection-string, you can see that the StorageSchema, ModelSchema and Mapping are specified in three different files (which are generated from your .edmx and than embedded in the assembly). 如果查看Entity Framework连接字符串,可以看到StorageSchema,ModelSchema和Mapping在三个不同的文件中指定(这些文件是从.edmx生成的,而不是嵌入在程序集中)。 You could take your .edmx apart and embed the .ssdl, .csdl and .msl yourself and than create another .ssdl for SQL Server CE. 您可以将.edmx分开并自己嵌入.ssdl,.csdl和.msl,然后为SQL Server CE创建另一个.ssdl。 This is basically just copy & paste and replacing the provider and some column-types. 这基本上只是复制和粘贴并替换提供程序和一些列类型。

I wrote about here: Comparison Entity Framework 我在这里写到: 比较实体框架

For Unit Tests I change Schema this way (changing ssdl before main code execution). 对于单元测试,我以这种方式更改Schema(在主代码执行之前更改ssdl)。

In code: 在代码中:

    var s = Assembly.GetExecutingAssembly().GetManifestResourceStream("Model1.ssdl");
    var ssdlFilePath = "<some-dir>\file1.ssdl";
    using (var file = File.Create(ssdlFilePath))
    {
        StreamUtil.Copy(s, file);
    }
    var str = File.ReadAllText(ssdlFilePath);
    str = str.Replace("old provider token", "ProviderManifestToken=\"4.0\"");
    str = str.Replace("old provider type"", "Provider=\"System.Data.SqlServerCe.4.0\"");
    File.WriteAllText(ssdlFilePath, str);

In app.config: 在app.config中:

  <connectionStrings>
    <add name="Database2Entities" connectionString="metadata=res://*/Model1.csdl|<some-dir>\file1.ssdl|res://*/Model1.msl;provider=System.Data.SqlServerCe.4.0;provider connection string=&quot;Data Source=|DataDirectory|\Database1.sdf&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

It works) 有用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM