Otávio Larrosa
Otávio Larrosa

Reputation: 303

Using Migrations with GenericContext

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 ?

Upvotes: 0

Views: 2511

Answers (3)

Victorio Berra
Victorio Berra

Reputation: 3105

I was able to wrap my typed context like so:

    public class CasbinDbContextTypeWrapper : CasbinDbContext<int>
    {
        public CasbinDbContextTypeWrapper(DbContextOptions<CasbinDbContextTypeWrapper> options) 
            : base(options)
        {
            // Intentionally empty
        }
    }

Upvotes: 0

Ivan Milosavljevic
Ivan Milosavljevic

Reputation: 839

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

Upvotes: 2

Michael Weinand
Michael Weinand

Reputation: 401

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://learn.microsoft.com/en-us/ef/core/modeling/included-types

Upvotes: 2

Related Questions