0

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 ?

2
  • 2
    The exception message is telling you 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. I don't see what do you expect from us - implement something which is not supported?
    – Ivan Stoev
    Nov 29, 2017 at 19:43
  • benjii.me/2016/06/… Nov 29, 2017 at 21:39

3 Answers 3

2

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

2

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
0

I was able to wrap my typed context like so:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.