简体   繁体   中英

Entity Framework Core use windows service

Currently in the process of building a multi tired application using EF Core for my data access layer and I feel like I'm running in to a problem and I'm not 100% certain I can use it at the moment.

Essentially I'm designing my application into the following components

  • windows assembly
  • asp.net mvc core web app
  • windows service x2
  • unit test

in good design I'm putting as much of my domain in my assembly so that I can reuse it as much as possible, but this is where I'm running into issues. I'm currently unable to use EF in my unit test app.

I am currently overriding OnConfiguring to set the database connection string but when I attempt to use the context in a unit testI continually get the following exception message: "Instance failure"

My context is dirt simple right now and only has one entity and looks as follows:

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; }
 }

In an effort to rule out the unit test as the problem I've also created a simple console application and even it throws the same exception so I'm really lost as to how to proceed.

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

The question is what am I doing that's wrong where I am unable to use a EF context from a windows assembly in any type of project aside from an ASP.NET Core MVC app?

This error - "Instance failure" - occurs when you copy/paste the connection string from your aspnetcore app, and still have escaped backslashes .

Outside of ASP.Net Core, ie a console/windows service etc, the connection string in the app.config does not need to escape the backslashes.

EG

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

rather then

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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