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:
Why EF Core is restricted to
ASP.Net Core
? Are all the projects in the world written withASP.Net Core
?Does anyone have experience working with EF core along with Windows Application or Console project and help to solve the issues?
Thanks