Using Migrations with GenericContext

.net-core ef-migrations entity-framework-core

Question

i'm trying to use migrations, but I have the following issue

$ dotnet ef migrations add InitialMigration
No DbContext was found in assembly 'VirtualStore.Data'. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.

Here, my Context class

using Microsoft.EntityFrameworkCore;
using VirtualStore.Mapping.Mapping;

namespace VirtualStore.Data
{
    public class Context<T> : DbContext where T : Entity
    {

        public DbSet<T> Entity { get; set; }


        public Context()
        {
            Database.EnsureCreated();
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Data Source=DESKTOP-3UEM3PC;Initial Catalog=VIRTUALSTORE;Integrated Security=SSPI;");
            base.OnConfiguring(optionsBuilder);
        }
    }
}

And My Solution

enter image description here

Anyone knows what can I do, to use Migrations with this Architecture ?

1
0
11/29/2017 7:37:33 PM

Accepted Answer

You do not want your DbContext "Context" to be generic. Make "Context" not generic and include separate DbSet properties for each of the entity types you are mapping to the database.

https://docs.microsoft.com/en-us/ef/core/modeling/included-types

2
11/29/2017 10:24:38 PM

Popular Answer

Why are you creating generic DbContext? From look at your code you are limiting yourself to one entity per DbContext creation. For example imagine that you have to create Sale and related SaleItem(s). You would have to instantiate two DbContext objects instead of one... and that opens up whole set of problems.

My suggestion is not to create generic DbContext but to make DbSet generic. There are several ways of doing it but here is an example that I have done recently.

Also note that in this solution I had to use project and project-source switch:

dotnet ef migrations add InitialMigration -p ..\Freelanceme.Data -s ..\Freelanceme.WebApi


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow