实体框架核心使用Windows服务

Mar*_*one 2 c# entity-framework-core

目前正在使用EF Core为我的数据访问层构建一个多累应用程序,我觉得我正在遇到问题而且我不是100%肯定我现在可以使用它.

基本上我将我的应用程序设计为以下组件

  • 窗户装配
  • asp.net mvc核心网络应用程序
  • Windows服务x2
  • 单元测试

在良好的设计中,我将尽可能多的域名放入我的程序集中,以便尽可能多地重用它,但这是我遇到问题的地方.我目前无法在我的单元测试应用中使用EF.

我目前正在重写OnConfiguring以设置数据库连接字符串,但是当我尝试在单元testI中使用上下文时,我不断收到以下异常消息:"Instance failure"

我的上下文现在很简单,只有一个实体,如下所示:

public partial class CdiContext : DbContext
{
    private string ConnectionString { get; set; }
    private bool IsService { get; set; }
    public CdiContext(string connectionString, bool isService)
    {
        ConnectionString = connectionString;
        IsService = isService;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(ConnectionString);
    }

    public DbSet<Region> Regions { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)

为了排除单元测试作为问题我还创建了一个简单的控制台应用程序,甚至它抛出相同的异常,所以我真的迷失了如何继续.

 CdiContext context =  new CdiContext(@"Data Source=localhost\\SQLEXPRESS;Initial Catalog=herp-interface;Persist Security Info=True;User ID=sa;Password=herpaderp;Pooling=true", true);
 var regions = context.Regions.ToList();

 Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

问题是,除了ASP.NET核心MVC应用程序之外,我无法在任何类型的项目中使用Windows程序集中的EF上下文,这是我做错了什么?

Jam*_*ill 5

当您从aspnetcore应用程序复制/粘贴连接字符串并且仍然有转义反斜杠时,会发生此错误 - "实例失败".

在ASP.Net Core之外,即控制台/ Windows服务等,app.config中的连接字符串不需要转义反斜杠.

例如

 <add name="DefaultConnection" connectionString="Server=localhost\\SQLEXPRESS...
Run Code Online (Sandbox Code Playgroud)

而不是

 <add name="DefaultConnection" connectionString="Server=localhost\SQLEXPRESS...
Run Code Online (Sandbox Code Playgroud)