42

Im unable to scaffold a controller (MVC5 Controller with views, using Entity Framework) in Visual studio 2013 (update 3 and 4). The error message is below:

There was an error running the selected code generator:

A configuration for type 'Library.Morthwind.Models.Catgeory' has already been added. To reference the existing configuration use the Entity<T>() or ComplexType<T>() methods

I have created the models by selecting 'Reverse Engineer Code First' from the 'Entity Framework Power Tools Beta 4' Tool menu.

Any ideas about what might cause this error?

Deilan
  • 4,740
  • 3
  • 39
  • 52
SimonB
  • 421
  • 1
  • 4
  • 5
  • Please vote for this issue: https://connect.microsoft.com/VisualStudio/feedback/details/1087913/mvc-controller-scaffold-with-entity-framework-code-generator-error – Jogai Mar 10 '15 at 10:22

11 Answers11

40

I had the same issue today.

I had added some custom configuration for one of my Model classes to add a relationship using the fluent API. This was specified in my dbContext class in the OnModelCreating override using the following:

modelBuilder.Configurations.Add(new OrderConfiguration());

Commenting out the above line allowed the Controller scaffolding to run as expected.

VS 2013 update 2 had a problem with this and the scaffolding came up with an unhelpful error with no further information. In installed Update 3 and it gave just enough detail to track down the underlying issue.

Jeff.

Flat Eric
  • 7,971
  • 9
  • 36
  • 45
Jeff
  • 422
  • 3
  • 7
  • This works. I commented the .Adds at the bottom of my DbContext and built that project as this post suggests and that allowed the scaffold to work. I was using LongLe's ODataControllerWithContext template. There will be a mismatch if you specified a pluralized controller name, if so, modify the class name or the constructor, whatever suits you. – Bill Sep 11 '14 at 16:37
  • 6
    The problem still exists as of Update 4. Does anybody know, if there is an appropriate bug submission for MS? – Deilan Dec 12 '14 at 15:09
  • 7
    Don't forget to "build" your project after commenting out configuration.Add line. Then you can try scaffolding your controller. If not VS scaffolding still thinks you have a custom configuration. – Bogac Feb 12 '15 at 17:10
  • Still a problem for update 5. However this solution works IF you do as @Bogac suggests and rebuild after you comment out. – arame3333 Feb 29 '16 at 09:08
19

I've been having this issue too. Jeff's solution works in some cases. But as my DbContext grew with more models that had keys needing to be mapped I couldn't delete the Configurations.Add() methods because I would then get errors that EF couldn't find primary keys, etc...

I did discover that by changing my DBContext derived class to use IDbSet properties instead of DbSet I could generate the controllers and views just fine. However, for me this introduced another issue, IDbSet does not support the async methods.

It appears I can either generate non-async controllers with configurations in place or async methods without configuration classes.

If your context properties are of type DbSet, try changing them to IDbSet. If you aren't generating async controller methods this may work for you.

Brian Scott
  • 221
  • 1
  • 3
6

I also had the same issue and changing my context class to use IDbSet allowed me to successfully use the scaffolding to create a new controller. But since I didn't want to give up the async methods I changed the context back to use DbSet and that worked for me.

Gandyman
  • 61
  • 1
  • 1
3

Here is how I resolved this issue. I have Visual Studio 2013 Update 4.
I use EF Power Tools. Comment out all of the DbSet < ... > Inside OnModelCreating, only leave the object you are scaffolding: modelBuilder.Configurations.Add(new SomeTableDataMap());

At the bottom of my context class I did notice this got created: public System.Data.Entity.DbSet SomeTableDatas{ get; set; }

Oh: I also put this in my constructor but it's for something else, this.Configuration.LazyLoadingEnabled = false;

Seriously, this worked today, I've tried all of these solutions nothing worked for Update 4. I had this working in Update 2 and Update 3 using previous solutions. This is the most up-to-date solution for now.

Luke G
  • 31
  • 1
3

Simple workaround that worked for me (after trying many other solutions suggested here and other places in vain...).

In the scaffolding dialog I just added a new DataContext e.g. TempContext. All the scaffolding worked as expected and then I could simply move the generated code in TempContext into my original DbContext and renamed the TempContext in the generated controllers to the original DbContext.

Richard Houltz
  • 1,962
  • 1
  • 18
  • 24
1

There are already multiple workarounds posted for this issue. And in this comment, I will try to provide the underlying issue why this may be failing. [With the hope to make people aware of the root cause]

Let's say, you have a DbContext (to be specific, child class of DbContext) in your application, and you are trying to use a model class (let's say Model) and the DbContext and scaffolding controllers / views.

I am guessing that the DbContext did not have a "DbSet< Model > Models {get; set;}" property on it but the DbSet was nevertheless added to the DbContext using code in OnModelCreating method.

In the above case, scaffolding first tries to detect DbSet property on DbContext (by reflection only - so that does not detect if OnModelCreating has code to add the DbSet) and given it's not, scaffolding adds a DbSet property to the DbContext and then tries to scaffold using that DbContext , however when running the scaffolding, we create an instance of DbContext and we also call OnModelCreating , and at that point, scaffolding fails because there are multiple DbSet types with the same model in the DbContext (one added by scaffolding and one configured in code in OnModelCreating).

[This happens not only for the model being used but also for related models in that model , scaffolding adds DbSet properties for all related models]

[Also, one doesn't see the added DbSet's after the scaffolding is done because scaffolding rolls back any changes if the operation did not complete successfully, like Jeff mentioned , the error message was poor initially and was improved to give some hint to the user but it's still not super clear what's going on]

This is a bug in scaffolding , a simple work around would be to use DbSet property on DbContext for all related models of your model class instead of configuring them in OnModelCreating.

pradeep
  • 101
  • 4
0

I was getting a different error when trying to scaffold a controller with CRUD actions and views. In my case it was saying:

"There was an error running the selected code generator. Object instance not set to an instance of the object."

The problem was hard to find: I created a table in SQL Server but forgot to set the Primary Key for the table. Setting the Primary key and updating Entity Framework's .edmx file solved the problem.

Hope it helps.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
0

None of the rest of the answers worked for me. What I found out was that the issue only happened when scaffolding and adding Configurations using the Fluent API. So what I did was, instead of having separated files, each one having an Entity Configuration like this:

public class ApplicationUserMapConfiguration : EntityTypeConfiguration<ApplicationUserMap>
{
    public ApplicationUserMapConfiguration()
    {
        ToTable("ApplicationUserMap", "Users");
        HasKey(c => c.Id);
     }
}

And then adding this configuration to the DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Configurations.Add(new ApplicationUserMapConfiguration()); 
}

I just added the whole configuration inside the DbContext for every entity:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        //ApplicationUser

        modelBuilder.Entity<ApplicationUser>().HasKey(c => c.Id);
        modelBuilder.Entity<ApplicationUser>().ToTable("ApplicationUser", "Usuario");

        //Other entities...
    }

Now I can scaffold perfectly. I already submited and issue on the Mvc GitHub.

Also, if another error message raises up saying:

There was an error running the selected code generator: ‘Exception has been thrown by the target of an invocation.’

You should modify your DbContext constructor to:

public YourDbContext() : base("YourDbContext", throwIfV1Schema: false) { }
Hernan Demczuk
  • 395
  • 1
  • 3
  • 11
0

None of answers of this post worked for me. I handled this issue creating new context class through plus button in Add Controller scaffolding dialog. Once VS created controller and views, I just remove the created context class and change the the generated controller code to use my existing context class.

Important: This process will add a new connection string for the new context, dont forget to remove it as well.

Luty
  • 160
  • 3
  • 7
0

mine got fixed like this:

    public virtual DbSet<Category> Categories { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //--> EntityTypeConfiguration<Your Model Configuration>
        modelBuilder.Configurations.Add(new EntityTypeConfiguration<CategoryMapping>());  

        base.OnModelCreating(modelBuilder);
    }

DOn't forget Ctrl + Shift + B so your code compile (i'm not sure for single solution, but since mine is in another project in same solution, it should get compiled first)

Hassan Faghihi
  • 1,888
  • 1
  • 37
  • 55
0

I solved it by adding a try/catch on the code to OnModelCreating function inside the context class. Just keep the base.OnModelCreating(modelBuilder);

outside your try/catch

Anas Ghanem
  • 127
  • 7