Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架6 SQL Server Compact 3.5,不带配置文件_C#_.net_Entity Framework_Sql Server Ce_App Config - Fatal编程技术网

C# 实体框架6 SQL Server Compact 3.5,不带配置文件

C# 实体框架6 SQL Server Compact 3.5,不带配置文件,c#,.net,entity-framework,sql-server-ce,app-config,C#,.net,Entity Framework,Sql Server Ce,App Config,我正在尝试使用Entity Framework 6访问SQL Server Compact 3.5数据库 我的应用程序是Visual Studio扩展,无法向应用程序配置文件添加任何内容 如果我制作了一个简单的测试应用程序,我就可以毫无问题地连接到数据库。如果我尝试从类库访问数据库,它将失败并显示错误消息 指定的架构无效。错误: ProjectTemplate.ssdl(2,2):错误0152:未找到具有固定名称“System.Data.SqlServerCe.3.5”的ADO.NET提供程序的

我正在尝试使用Entity Framework 6访问SQL Server Compact 3.5数据库

我的应用程序是Visual Studio扩展,无法向应用程序配置文件添加任何内容

如果我制作了一个简单的测试应用程序,我就可以毫无问题地连接到数据库。如果我尝试从类库访问数据库,它将失败并显示错误消息

指定的架构无效。错误: ProjectTemplate.ssdl(2,2):错误0152:未找到具有固定名称“System.Data.SqlServerCe.3.5”的ADO.NET提供程序的实体框架提供程序。确保提供程序已在应用程序配置文件的“entityFramework”部分注册。有关更多信息,请参阅

例如,我发现了一些有趣的链接,但我无法使其正常工作,因为该示例适用于EF5或SQL Server(或者我的眼睛蒙上了毛)


怎么做?

我目前正在使用控制台应用程序和类库进行测试。控制台应用程序对实体框架一无所知,只调用类库中的方法

static void Main(string[] args)
{
  EFTest t = new EFTest();
  t.Test();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.EntityClient;

namespace EF6_SQLCompact_CleanTest_000
{
  public class EFTest
  {
    public void Test()
    {
      try
      {
        // Add an event handler for DbConfiguration.Loaded, which adds our dependency 
        // resolver class to the chain of resolvers.
        System.Data.Entity.DbConfiguration.Loaded += (_, a) => {
          a.AddDependencyResolver(new MyDependencyResolver(), true);
        };

        // Define the provider connection string, specifying the SQL Server Compact 3.5 filename.
        String FileName = @"f:\DotNetTestProjects\2015\CS\SQLCompact35DllTest\SQLCompact35DllTest\ProjectTemplate.sdf";
        String ConnectionString = String.Format("Data Source={0}", FileName);

        // Create the entity framework connection string, specifying the model,
        // the provider and the provider connection string.
        var builder = new EntityConnectionStringBuilder();
        builder.Metadata = @"res://*/ProjectTemplate.csdl|res://*/ProjectTemplate.ssdl|res://*/ProjectTemplate.msl";
        builder.Provider = "System.Data.SqlServerCe.3.5";
        builder.ProviderConnectionString = ConnectionString;

        // Create the entity framework kontext
        Entities Context = new Entities(builder.ToString());

        // Do a trivial query as a test.
        int i = Context.Languages.Count();
        MessageBox.Show(i.ToString());
      }
      catch (Exception e)
      {
        MessageBox.Show(e.Message);
      }
    }
  }

  // Define an additional constructor for the Entities class, so that we can 
  // pass the connection string into the base class DbContext.
  public partial class Entities : DbContext
  {
    public Entities(String ConnectionString)
      : base(ConnectionString)
    {
    }
  }

  class MyDependencyResolver : System.Data.Entity.Infrastructure.DependencyResolution.IDbDependencyResolver
  {
    public object GetService(Type type, object key)
    {
      // Output the service attempting to be resolved along with it's key 
      System.Diagnostics.Debug.WriteLine(string.Format("MyDependencyResolver.GetService({0}, {1})", type.Name, key == null ? "" : key.ToString()));

      if ((type == typeof(System.Data.Common.DbProviderFactory))
           && (key != null)
           && ((string)(key) == "System.Data.SqlServerCe.3.5"))
      {
        return System.Data.SqlServerCe.SqlCeProviderFactory.Instance ;
      }
      else if ((type == typeof(System.Data.Entity.Core.Common.DbProviderServices))
                && (key != null)
                && ((string)(key) == "System.Data.SqlServerCe.3.5"))
      {
        return System.Data.Entity.SqlServerCompact.Legacy.SqlCeProviderServices.Instance ;
      }
      else if ((type == typeof(System.Data.Entity.Infrastructure.IProviderInvariantName))
                && (key is System.Data.SqlServerCe.SqlCeProviderFactory))
      {
        return new MyProviderInvariantName();
      }

      return null;
    }

    public IEnumerable<object> GetServices(Type type, object key)
    {
      return new object[] { GetService(type, key) }.ToList().Where(o => o != null);
    }
  }

  // Implement IProviderInvariantName so that we can return an object when
  // requested in GetService()
  class MyProviderInvariantName : IProviderInvariantName
  {
    public string Name
    {
      get { return "System.Data.SqlServerCe.3.5"; }
    }
  }
}
这是类库中的代码

static void Main(string[] args)
{
  EFTest t = new EFTest();
  t.Test();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.EntityClient;

namespace EF6_SQLCompact_CleanTest_000
{
  public class EFTest
  {
    public void Test()
    {
      try
      {
        // Add an event handler for DbConfiguration.Loaded, which adds our dependency 
        // resolver class to the chain of resolvers.
        System.Data.Entity.DbConfiguration.Loaded += (_, a) => {
          a.AddDependencyResolver(new MyDependencyResolver(), true);
        };

        // Define the provider connection string, specifying the SQL Server Compact 3.5 filename.
        String FileName = @"f:\DotNetTestProjects\2015\CS\SQLCompact35DllTest\SQLCompact35DllTest\ProjectTemplate.sdf";
        String ConnectionString = String.Format("Data Source={0}", FileName);

        // Create the entity framework connection string, specifying the model,
        // the provider and the provider connection string.
        var builder = new EntityConnectionStringBuilder();
        builder.Metadata = @"res://*/ProjectTemplate.csdl|res://*/ProjectTemplate.ssdl|res://*/ProjectTemplate.msl";
        builder.Provider = "System.Data.SqlServerCe.3.5";
        builder.ProviderConnectionString = ConnectionString;

        // Create the entity framework kontext
        Entities Context = new Entities(builder.ToString());

        // Do a trivial query as a test.
        int i = Context.Languages.Count();
        MessageBox.Show(i.ToString());
      }
      catch (Exception e)
      {
        MessageBox.Show(e.Message);
      }
    }
  }

  // Define an additional constructor for the Entities class, so that we can 
  // pass the connection string into the base class DbContext.
  public partial class Entities : DbContext
  {
    public Entities(String ConnectionString)
      : base(ConnectionString)
    {
    }
  }

  class MyDependencyResolver : System.Data.Entity.Infrastructure.DependencyResolution.IDbDependencyResolver
  {
    public object GetService(Type type, object key)
    {
      // Output the service attempting to be resolved along with it's key 
      System.Diagnostics.Debug.WriteLine(string.Format("MyDependencyResolver.GetService({0}, {1})", type.Name, key == null ? "" : key.ToString()));

      if ((type == typeof(System.Data.Common.DbProviderFactory))
           && (key != null)
           && ((string)(key) == "System.Data.SqlServerCe.3.5"))
      {
        return System.Data.SqlServerCe.SqlCeProviderFactory.Instance ;
      }
      else if ((type == typeof(System.Data.Entity.Core.Common.DbProviderServices))
                && (key != null)
                && ((string)(key) == "System.Data.SqlServerCe.3.5"))
      {
        return System.Data.Entity.SqlServerCompact.Legacy.SqlCeProviderServices.Instance ;
      }
      else if ((type == typeof(System.Data.Entity.Infrastructure.IProviderInvariantName))
                && (key is System.Data.SqlServerCe.SqlCeProviderFactory))
      {
        return new MyProviderInvariantName();
      }

      return null;
    }

    public IEnumerable<object> GetServices(Type type, object key)
    {
      return new object[] { GetService(type, key) }.ToList().Where(o => o != null);
    }
  }

  // Implement IProviderInvariantName so that we can return an object when
  // requested in GetService()
  class MyProviderInvariantName : IProviderInvariantName
  {
    public string Name
    {
      get { return "System.Data.SqlServerCe.3.5"; }
    }
  }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
使用System.Data.Entity;
使用System.Data.Entity.Infrastructure;
使用System.Data.Entity.Core.EntityClient;
名称空间EF6\u SQLCompact\u CleanTest\u 000
{
公共类EFT测试
{
公开无效测试()
{
尝试
{
//为DbConfiguration.Loaded添加一个事件处理程序,这将添加我们的依赖项
//解析程序类到解析程序链。
System.Data.Entity.DbConfiguration.Loaded+=(\ux,a)=>{
a、 AddDependencyResolver(新的MyDependencyResolver(),true);
};
//定义提供程序连接字符串,指定SQL Server Compact 3.5文件名。
字符串文件名=@“f:\DotNetTestProjects\2015\CS\SQLCompact35DllTest\SQLCompact35DllTest\ProjectTemplate.sdf”;
String ConnectionString=String.Format(“数据源={0}”,文件名);
//创建实体框架连接字符串,指定模型,
//提供程序和提供程序连接字符串。
var builder=新的EntityConnectionStringBuilder();
元数据=@“res://*/ProjectTemplate.csdl | res://*/ProjectTemplate.ssdl | res://*/ProjectTemplate.msl”;
builder.Provider=“System.Data.SqlServerCe.3.5”;
builder.ProviderConnectionString=ConnectionString;
//创建实体框架文本
实体上下文=新实体(builder.ToString());
//做一个简单的查询作为测试。
int i=Context.Languages.Count();
Show(i.ToString());
}
捕获(例外e)
{
MessageBox.Show(e.Message);
}
}
}
//为Entities类定义一个额外的构造函数,以便
//将连接字符串传递到基类DbContext中。
公共部分类实体:DbContext
{
公共实体(字符串连接字符串)
:基本(连接字符串)
{
}
}
类MyDependencyResolver:System.Data.Entity.Infrastructure.DependencyResolver.IDBDendencyResolver
{
公共对象GetService(类型,对象键)
{
//输出试图解析的服务及其密钥
System.Diagnostics.Debug.WriteLine(string.Format(“MyDependencyResolver.GetService({0},{1})”,type.Name,key==null?”:key.ToString());
if((type==typeof(System.Data.Common.DbProviderFactory))
&&(键!=null)
&&((字符串)(键)=“System.Data.SqlServerCe.3.5”))
{
返回System.Data.SqlServerCe.SqlCeProviderFactory.Instance;
}
else if((type==typeof(System.Data.Entity.Core.Common.DbProviderServices))
&&(键!=null)
&&((字符串)(键)=“System.Data.SqlServerCe.3.5”))
{
返回System.Data.Entity.SqlServerCompact.Legacy.SqlCeProviderServices.Instance;
}
else if((type==typeof(System.Data.Entity.Infrastructure.IProviderInvariantName))
&&(关键是System.Data.SqlServerCe.SqlCeProviderFactory)
{
返回新的MyProviderInvariantName();
}
返回null;
}
公共IEnumerable GetServices(类型、对象键)
{
返回新对象[]{GetService(type,key)}.ToList(),其中(o=>o!=null);
}
}
//实现IProviderInvariantName,以便在
//在GetService()中请求
类MyProviderInvariantName:IPProviderInVariantName
{
公共字符串名
{
获取{return“System.Data.SqlServerCe.3.5”;}
}
}
}
依赖项解析器基于EricEJ提到的链接中Ryan Griffith的答案

这似乎在我的测试程序的上下文中起作用,但我还没有在VisualStudio扩展的上下文中尝试过


据我所知,只有在首次在AppDomain中加载DbConfiguration之前(我可能无法保证)将事件处理程序添加到DbConfiguration.Loaded中,此技术才会起作用。我还担心它可能会对Visual Studio或其他Visual Studio扩展产生副作用。

我目前正在使用控制台应用程序和类库进行测试。控制台应用程序对实体框架一无所知,只调用类库中的方法

static void Main(string[] args)
{
  EFTest t = new EFTest();
  t.Test();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.EntityClient;

namespace EF6_SQLCompact_CleanTest_000
{
  public class EFTest
  {
    public void Test()
    {
      try
      {
        // Add an event handler for DbConfiguration.Loaded, which adds our dependency 
        // resolver class to the chain of resolvers.
        System.Data.Entity.DbConfiguration.Loaded += (_, a) => {
          a.AddDependencyResolver(new MyDependencyResolver(), true);
        };

        // Define the provider connection string, specifying the SQL Server Compact 3.5 filename.
        String FileName = @"f:\DotNetTestProjects\2015\CS\SQLCompact35DllTest\SQLCompact35DllTest\ProjectTemplate.sdf";
        String ConnectionString = String.Format("Data Source={0}", FileName);

        // Create the entity framework connection string, specifying the model,
        // the provider and the provider connection string.
        var builder = new EntityConnectionStringBuilder();
        builder.Metadata = @"res://*/ProjectTemplate.csdl|res://*/ProjectTemplate.ssdl|res://*/ProjectTemplate.msl";
        builder.Provider = "System.Data.SqlServerCe.3.5";
        builder.ProviderConnectionString = ConnectionString;

        // Create the entity framework kontext
        Entities Context = new Entities(builder.ToString());

        // Do a trivial query as a test.
        int i = Context.Languages.Count();
        MessageBox.Show(i.ToString());
      }
      catch (Exception e)
      {
        MessageBox.Show(e.Message);
      }
    }
  }

  // Define an additional constructor for the Entities class, so that we can 
  // pass the connection string into the base class DbContext.
  public partial class Entities : DbContext
  {
    public Entities(String ConnectionString)
      : base(ConnectionString)
    {
    }
  }

  class MyDependencyResolver : System.Data.Entity.Infrastructure.DependencyResolution.IDbDependencyResolver
  {
    public object GetService(Type type, object key)
    {
      // Output the service attempting to be resolved along with it's key 
      System.Diagnostics.Debug.WriteLine(string.Format("MyDependencyResolver.GetService({0}, {1})", type.Name, key == null ? "" : key.ToString()));

      if ((type == typeof(System.Data.Common.DbProviderFactory))
           && (key != null)
           && ((string)(key) == "System.Data.SqlServerCe.3.5"))
      {
        return System.Data.SqlServerCe.SqlCeProviderFactory.Instance ;
      }
      else if ((type == typeof(System.Data.Entity.Core.Common.DbProviderServices))
                && (key != null)
                && ((string)(key) == "System.Data.SqlServerCe.3.5"))
      {
        return System.Data.Entity.SqlServerCompact.Legacy.SqlCeProviderServices.Instance ;
      }
      else if ((type == typeof(System.Data.Entity.Infrastructure.IProviderInvariantName))
                && (key is System.Data.SqlServerCe.SqlCeProviderFactory))
      {
        return new MyProviderInvariantName();
      }

      return null;
    }

    public IEnumerable<object> GetServices(Type type, object key)
    {
      return new object[] { GetService(type, key) }.ToList().Where(o => o != null);
    }
  }

  // Implement IProviderInvariantName so that we can return an object when
  // requested in GetService()
  class MyProviderInvariantName : IProviderInvariantName
  {
    public string Name
    {
      get { return "System.Data.SqlServerCe.3.5"; }
    }
  }
}
这是类库中的代码

static void Main(string[] args)
{
  EFTest t = new EFTest();
  t.Test();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.EntityClient;

namespace EF6_SQLCompact_CleanTest_000
{
  public class EFTest
  {
    public void Test()
    {
      try
      {
        // Add an event handler for DbConfiguration.Loaded, which adds our dependency 
        // resolver class to the chain of resolvers.
        System.Data.Entity.DbConfiguration.Loaded += (_, a) => {
          a.AddDependencyResolver(new MyDependencyResolver(), true);
        };

        // Define the provider connection string, specifying the SQL Server Compact 3.5 filename.
        String FileName = @"f:\DotNetTestProjects\2015\CS\SQLCompact35DllTest\SQLCompact35DllTest\ProjectTemplate.sdf";
        String ConnectionString = String.Format("Data Source={0}", FileName);

        // Create the entity framework connection string, specifying the model,
        // the provider and the provider connection string.
        var builder = new EntityConnectionStringBuilder();
        builder.Metadata = @"res://*/ProjectTemplate.csdl|res://*/ProjectTemplate.ssdl|res://*/ProjectTemplate.msl";
        builder.Provider = "System.Data.SqlServerCe.3.5";
        builder.ProviderConnectionString = ConnectionString;

        // Create the entity framework kontext
        Entities Context = new Entities(builder.ToString());

        // Do a trivial query as a test.
        int i = Context.Languages.Count();
        MessageBox.Show(i.ToString());
      }
      catch (Exception e)
      {
        MessageBox.Show(e.Message);
      }
    }
  }

  // Define an additional constructor for the Entities class, so that we can 
  // pass the connection string into the base class DbContext.
  public partial class Entities : DbContext
  {
    public Entities(String ConnectionString)
      : base(ConnectionString)
    {
    }
  }

  class MyDependencyResolver : System.Data.Entity.Infrastructure.DependencyResolution.IDbDependencyResolver
  {
    public object GetService(Type type, object key)
    {
      // Output the service attempting to be resolved along with it's key 
      System.Diagnostics.Debug.WriteLine(string.Format("MyDependencyResolver.GetService({0}, {1})", type.Name, key == null ? "" : key.ToString()));

      if ((type == typeof(System.Data.Common.DbProviderFactory))
           && (key != null)
           && ((string)(key) == "System.Data.SqlServerCe.3.5"))
      {
        return System.Data.SqlServerCe.SqlCeProviderFactory.Instance ;
      }
      else if ((type == typeof(System.Data.Entity.Core.Common.DbProviderServices))
                && (key != null)
                && ((string)(key) == "System.Data.SqlServerCe.3.5"))
      {
        return System.Data.Entity.SqlServerCompact.Legacy.SqlCeProviderServices.Instance ;
      }
      else if ((type == typeof(System.Data.Entity.Infrastructure.IProviderInvariantName))
                && (key is System.Data.SqlServerCe.SqlCeProviderFactory))
      {
        return new MyProviderInvariantName();
      }

      return null;
    }

    public IEnumerable<object> GetServices(Type type, object key)
    {
      return new object[] { GetService(type, key) }.ToList().Where(o => o != null);
    }
  }

  // Implement IProviderInvariantName so that we can return an object when
  // requested in GetService()
  class MyProviderInvariantName : IProviderInvariantName
  {
    public string Name
    {
      get { return "System.Data.SqlServerCe.3.5"; }
    }
  }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
使用System.Data.Entity;
使用System.Data.Entity.Infrastructure;
使用System.Data.Entity.Core.EntityClient;
名称空间EF6\u SQLCompact\u CleanTest\u 000
{
公共类EFT测试
{
公众假期