实体框架核心使用Windows服务

时间:2016-03-18 12:45:52

标签: c# entity-framework-core

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

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

  • windows assembly
  • asp.net mvc核心网络应用
  • windows service 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; }
 }

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

 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();

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

1 个答案:

答案 0 :(得分:5)

此错误 - “实例失败” - 从您的aspnetcore应用程序复制/粘贴连接字符串时仍然出现转义反斜杠

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

EG

 <add name="DefaultConnection" connectionString="Server=localhost\\SQLEXPRESS...

而不是

 <add name="DefaultConnection" connectionString="Server=localhost\SQLEXPRESS...