0

I'm just learning Entity Framework Core 3.1. I wondering why all learning contents learn it using ASP.Net Core!! So I decide to test some of the codes on a Class Library along withConsole Application. This is my very simple class library code:

public class ApplicationDbContext : DbContext
{
    private static readonly string ConnectionString = "Server=.;Database=Northwind;Trusted_Connection=True;";
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    public DbSet<NimaCategory> NimaCategories { get; set; }

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration(new NimaCategoryConfig());
    }
}

I faced many strange errors for creating Migration but strangest is I must write all of these line of codes to my Console Application:

public class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello EF Core")
    }
    public static IHostBuilder CreateHostBuilder(string[] args)
                    => Host.CreateDefaultBuilder(args)
                        .ConfigureWebHostDefaults(
                            webBuilder => webBuilder.UseStartup<Startup>());

}
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
        => services.AddDbContext<ApplicationDbContext>();
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    }
}

and the problem is IHostBuilder and ConfigureWebHostDefaults are for ASP.Net Core and it's dependency injection engine. So based on the below link I change my csproj file:

IHostBuilder does not contain a definition for ConfigureWebHostDefaults

Now I can't run my console application because It's nature has changed and converted to Web project. Then I add a window application and I can't add these codes for configurations:

public static IHostBuilder CreateHostBuilder(string[] args)
                    => Host.CreateDefaultBuilder(args)
                        .ConfigureWebHostDefaults(
                            webBuilder => webBuilder.UseStartup<Startup>());

and:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
        => services.AddDbContext<ApplicationDbContext>();
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    }
}

I have some questions about this problems:

  1. Why EF Core is restricted to ASP.Net Core? Are all the projects in the world written with ASP.Net Core?

  2. Does anyone have experience working with EF core along with Windows Application or Console project and help to solve the issues?

Thanks

Arian
  • 12,793
  • 66
  • 176
  • 300
  • EF is not restricted to ASP. You can use it in Console and desktop applications. – Guru Stron Oct 20 '20 at 21:47
  • Also can you please share "many strange errors" you get? – Guru Stron Oct 20 '20 at 21:48
  • @GuruStron Can you show some reference to work `EF Core` in the way I'm using it? I searched the interent but I didn't find any thing – Arian Oct 20 '20 at 21:48
  • @GuruStron. this is one of those: unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 – Arian Oct 20 '20 at 21:49
  • @GuruStron Can you please create two projects: one `Class Library` and one is `Console Application` so Insert one record in one simple table? – Arian Oct 20 '20 at 21:53
  • Try creating design time db context as the link suggests. Not sure maybe migration tool needs correctly set up [host](https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host) so you can use it. – Guru Stron Oct 20 '20 at 21:53
  • 1
    I have a [GitHub repository](https://github.com/karenpayneoregon/NorthWind-2020) that has code samples for win forms using a revised version of MS-NorthWind database. None of the code samples are meant to be real apps but instead for showing what's possible. [Try this project](https://github.com/karenpayneoregon/NorthWind-2020/tree/master/North) which is set to display a DataGridView with immediate updates, has DataGridViewComboBox columns and permits sorting. Poke around the other 26 projects for ideas too. Note there are no migrations - code first existing db. – Karen Payne Oct 21 '20 at 13:44

3 Answers3

0

You can use EF Core everywhere.

Make a Console application project then install these packages

  1. https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer/3.1.9

  2. https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools/3.1.9

and put your connection string in OnConfiguringMethod.

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
  optionsBuilder.UseSqlServer("Server=serverName;Database=dbName;Trusted_Connection=True;MultipleActiveResultSets=True");
}

and voila you can learn ef core in console app. they just teach ef core with ASP.NET Core because of UI.

and i think Julie Lerman Teaches EF Core in Console app, you can use Pluralsight platform for EF Core tutorials.

Armin Shoeibi
  • 580
  • 6
  • 18
  • Thanks dear friend but when I want to `add-migration` I got this error: **Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728** – Arian Oct 20 '20 at 22:16
  • make sure that you just have one project in your solution, and make a custom class for DbContext in that project. – Armin Shoeibi Oct 20 '20 at 22:29
  • It's the problem. I have 2 projects: 1 class library and 1 console app. My console app reference to my class library. Why it's restrict?! – Arian Oct 20 '20 at 22:34
  • That's bizarre, when you try to add-migration check the project that selected in Package manager console, you need to select the project that contains DbContext class in it. – Armin Shoeibi Oct 20 '20 at 22:36
  • Yes I checked it before and I select my class library project – Arian Oct 21 '20 at 06:08
0

Here are some answers, as well as what I use to get my EF Core working.

Why EF Core is restricted to ASP.Net Core? Are all the projects in the world written with ASP.Net Core?

It's not restricted to ASP.Net Core, EF Core and Core itself is simply a console application. And no all projects in the work are not build with ASP.NET Core --- However, due to it's flexibility Microsoft is dropping support for all other versions of .Net. Meaning the next Release of .Net will actually be .NetCore. If you are building for a normal .Net application, it might be better to use EF 6 instead of Core. Core just allows crossplatform capabilities.

Does anyone have experience working with EF core along with Windows Application or Console project and help to solve the issues?

Well yes, also all Core applications are Console Projects. So if you are able to do it in a windows application you are able to do it in Core.


But now I will show you what I do. I work for a company and use EF core on multiple projects, my basic formula looks like this:

Nuget Packages:

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Relational

Here is the code in the Startup file. Note it will look slightly different than yours because I put my Dbcontext in a different project than my entry point.

public void ConfigureServices(IServiceCollection services)
{
    // Add the SQL db conneciton
    /*
        AddSQLContext is just a function in a different project. Not Needed
    */
    services.AddSQLContext(options => options.UseSqlServer(
    
        // This is simply the connection stirng
        Configuration.GetConnectionString("SqlConnection"),
        
        // We add a migration assembly only if the EF core DbContext is in another project
        actions => actions.MigrationsAssembly("My.Other.Project.Assembly")
    ));
                
}

My code for calling the Context is in another project. I like to keep it seperate. But you don't have to do that. Here are the Nuget packages I use, But I think the Tools and Design are only neccecary when doing a CodeFirst approach (building Database from EF core instead of Scaffolding):

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.SqlServer.Design
Microsoft.EntityFrameworkCore.Tools

public static class ServiceCollectionExtentions
{
    /*
        SqlContext is my own custom context similar to your [ ApplicationDbContext ]
    */
    public static IServiceCollection AddSQLContext(this IServiceCollection services, Action<DbContextOptionsBuilder> options) => services
            .AddDbContext<SqlContext>(options);
            
}

public class SqlContext : DbContext
{
    public SqlContext(DbContextOptions options)
        : base(options){}

    
    ...
    
}
Cornelis
  • 1,065
  • 8
  • 23
  • Thanks but I have several questions about it: 1) In Console application what is `Startup` class? 2)Where should I write `ConfigureServices` class? 3)Where should I write `ServiceCollectionExtentions` class? – Arian Oct 21 '20 at 06:48
0

The solution is very simple: just add default constructor for the ApplicationDbContext:

public ApplicationDbContext()
{
}
Arian
  • 12,793
  • 66
  • 176
  • 300