Solmead
Solmead

Reputation: 4199

How do I use asp.net MVC Scaffolder with a context that is two subclasses down from dbcontext

I have a standard model set.

I have a base context class that inherits from dbcontext to add some features I needed.

public class MyContext : DbContext
{
    public void MyFeature() {
    }
}

I then have my actual Data Context:

public class DataContext : MyContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
}

I want to use the scaffolder built in when you create a controller, but I get an error "Unsupported Context Type" If I change the datacontext to just inherit from dbcontext directly it works, but at this point I have alot of stuff that uses the added features, so changing the inheritance cant be done without commenting out all that stuff. And I have of course simplified down the features, it is actually quite alot of stuff, so adding it directly into the datacontext would be alot of work, plus the scaffolder should be smart enough to see that the datacontext is a dbcontext.

How can I use the scaffolder with my datacontext?

Upvotes: 3

Views: 611

Answers (2)

Rajpurohit
Rajpurohit

Reputation: 1991

i think first you should install entity framework 4.0 then i think definitely it's working please try this.

Upvotes: 0

Nate-Wilkins
Nate-Wilkins

Reputation: 5492

Why don't you use Composition?

If your feature really is just needed as lets say a few methods needed in those objects I would put those methods in a separate class called ContextDetails - something along those lines and have DataContext contain a ContextDetails like so:

//Changed MyContext to ContextDetails
public class ContextDetails 
{
    public void MyFeature() 
    {
        //Do something
    }
}

public class DataContext : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }

    public ContextDetails DbDetails { get; set; }
}

And if the ContextDetails object needs information about the DataContext/DbContext it's in pass the DataContext/DbContext into a method or even the constructor.

If you don't like Composition for this problem maybe you want to use an Interface. If that's the case check out http://www.codeproject.com/Tips/309753/Repository-Pattern-with-Entity-Framework-4-1-and-C

The context class must inherit from System.Data.EntityDbContext which provides facilities for querying and working with entity data as objects

The best reason I could find for why the inheritance is not working in your example.

EDIT:

I read my answer and realized DBDetails might not be the best name but you get the idea. Extract the implementation and use it as a separate entity. Good luck!

Upvotes: 2

Related Questions