Scaffolding: Could not get the reflection type for DbContext

Created on 25 Mar 2017  路  19Comments  路  Source: dotnet/Scaffolding

Error

There was an error running the selected code generator:

'Could not get the reflection type for DbContext : MyProject.Data.MyDbContext
at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)'

In VS2017 RTM community edition, ASPNET Core 1.1 app

After a lot of wondering how this suddenly started to happen in projects which would scaffold controller and views with no problem and then suddenly I would start getting this error.

After many many hours of searching for a solution and a lot of experimentation with controllers and data annotations etc etc... I found while search google for an answer I found a person who also had the problem and offered a solution.

This persons solution did not solve the issue, but it lead me to realize why in my case the error was occurring. The offered solution was to use the new controller dialog to make a new controller for the class I wanted to make the controller and views for. while this did not work, it did offer a different error message which lead me to the answer of why I could no loner auto generate controllers and views.

What I found was in my web application was when I created a "Service" class which used the IMemoryCache in it to cache data I got this error.

For example I have a service class which creates the menu structure for parts of the website menu from information in the database, when I cached the menu structure as it does not change very often using the IMemoryCache in the service class I get the error.

Once I remove the caching of the menu service class I can use the controller dialog to generate Controller and Views again.

Then I also notice in another service I have which caches news Items even just having the IMemoryCache setup on the service which is not even been used, I just created the news service class I had not even used it, it was just sitting in my project, this also made the above error occur when trying to generate a controller and it's views via the controllers dialog.

In both of the above cases the objects that I was caching were not objects from the database/dbcontext, they were objects I created from in the first case data from the database and poulated a simple two property object for the menu item and in the second case the object cached was an objected created from a call to a web-service, but information from the database is used to make the call to the web-service.

But in both cases they are just POCO (non database/dbcontext objects) that were cached using IMemoryCache via DI in the service class

Most helpful comment

currently there is no way to support scaffolding in this scenario for 1.0 and 1.1 versions.

Update:

There is a workaround to let scaffolding in versions 1.0 and 1.1 work with C#7 code.

  • Install (or update) NuGet package Microsoft.CodeAnalysis.CSharp.Workspaces version 2.0.0 or higher to the project.
  • Restore and retry scaffolding.

All 19 comments

@dotnetnoobie Can you share a sample project in which this issue can be repro'ed?

@prafullbhosale I have made a new blank web project to just reproduce the issue and I found out exactly causes the error

It's a new C#7 feature that causes it when you are trying to scaffold a Controller and it's Views.

If I have a service setup in this fashion, the scaffolding works correctly

var key = "people-menu";
List<MenuItem> data;
if (_cache.TryGetValue(key, out data)) return data;
data = _context.People.Select(x => new MenuItem { Id = x.PersonId, Text = x.FirstName }).ToList();
_cache.Set(key, data, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(1)));

return data;

This version will cause the error to occur when I try to use scaffolding

var key = "people-menu";
if (_cache.TryGetValue(key, out List<MenuItem> data)) return data;
data = _context.People.Select(x => new MenuItem { Id = x.PersonId, Text = x.FirstName }).ToList();
_cache.Set(key, data, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(1)));

return data;

The error occurs when you use the new C#7 feature to put the declaration inline in the
_cache.TryGetValue(key, out List<MenuItem> data)

This is slightly different where I have a new object to hold the list after trying to see if it already exists in the cache

Scaffolding works

var key = $"teams-menu";
List<MenuItem> data;
if (_cache.TryGetValue(key, out data)) return data;
var items = _context.Teams.Select(x => new MenuItem { Id = x.TeamId, Text = x.Name }).ToList();
_cache.Set(key, items, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(1)));

return items;

Even using a different object like below will cause the error

var key = $"teams-menu";
if (_cache.TryGetValue(key, out List<MenuItem> data)) return data;
var items = _context.Teams.Select(x => new MenuItem { Id = x.TeamId, Text = x.Name }).ToList();
_cache.Set(key, items, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(1)));

return items;

So basically it boils down to the line(s)

This works in scaffolding

List<MenuItem> data;
if (_cache.TryGetValue(key, out data)) return data;

This fails in scaffolding
(_cache.TryGetValue(key, out List<MenuItem> data)

@prafullbhosale Here is the demo project https://github.com/dotnetnoobie/ScaffoldingErrorDemo
it's just bare bones to show the issue

There is a Service class called PersonService.cs
it has two versions of a method called GetPeople()
with a comment above each method saying if it works or fails with scaffolding

In the DataContext for the project are to classes which you can use to try to scaffold
Person.cs
Team.cs

Here is a sample with this error also. The commented works ok, if I uncomment // : IEntityBase generator fails

public abstract class EntityGuidBase// : IEntityBase<Guid>
    {
        [Key]
        public virtual Guid Id { get; set; }

        //object IEntityBase.Id
        //{
        //    get => this.Id;

        //    set => this.Id = (Guid)value;
        //}
    }
public abstract class EntityBase// : IEntityBase<int>
    {
        public virtual int Id { get; set; }

        //object IEntityBase.Id
        //{
        //    get => this.Id;

        //    set => this.Id = (int)value;
        //}
    }

public class Category : EntityBase
    {
        [Required]
        public string Name { get; set; }

        public string Code { get; set; }

        public string Desc { get; set; }

        public int? ParentId { get; set; }

        public virtual  Category Parent { get; set; }

        public int Left { get; set; }

        public int Right { get; set; }

        public virtual Guid ConcurrencyStamp { get; set; } = Guid.NewGuid();
    }

@dotnetnoobie the error in your case the error is due to https://github.com/aspnet/Scaffolding/issues/410

@xumix the error in your case is also related to #410

If i change

        //object IEntityBase.Id
        //{
        //    get => this.Id;

        //    set => this.Id = (int)value;
        //}

to

        object IEntityBase.Id
        {
            get { return this.Id; } 

            set { this.Id = (int)value; }
        }

and same change for EntityGuidBase, I am able to scaffold.

@prafullbhosale I actually target a.netcoreapp1.1, is it lower than 4.6?

I also having this issue when I use the new C#7 feature (declaring out variables inline)
This not work
SomeMethod(out bool param1, out string param2);
This work:

bool param1;
string param2;
SomeMethod(out bool param1, out string param2);

Error Generating a View with "Data Context class" set:

There was an error creating a DbContext :C:projects...: error CS1525: Invalid expression term 'bool'
C:projects...: error CS1003: Syntax error, ',' expected
C:projects...: error CS1525: Invalid expression term 'string'
C:projects...: error CS1003: Syntax error, ',' expected
C:projects...: error CS0103: The name 'param1' does not exist in the current context
C:projects...: error CS0103: The name 'param2' does not exist in the current context
at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)

Error Generating a View with no "Data Context class" set:

Could not get the reflection type for Model : SomeViewModel
at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)
RunTime 00:00:06.14

@xumix, the issue is not with the target framework of your project. The Roslyn packages that scaffolding 1.0.0 and 1.1.0 depends on does not support C#7 features.
We are upgrading the Roslyn package dependencies to newer ones, however the newer Roslyn packages do not support TFM < net46 which is what the discussion in #410 is about.

I'm working in an MVC proyect, on VS2017 RTM, ASPNET Core 1.1.

Suddenly when I tried to scaffold a class (successfully scaffolded before), hit the error.

Could not get the reflection type for DbContext : App.Models.ApplicationDbContext
at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)
RunTime 00:00:09.64

Reading this article gave me the hint I needed to identify the issue...

At some point, VS2017 Intellisense suggested me to abbreviate, or change a getter from this format...

public string fieldName
{
    get
    {
        return "some value";
    }
    private set { }
}

to this one....

public string fieldName
{
    get => "some value";
    private set { }
}

When I rolled back that change, the scaffold worked like a charm.

Thank you everyone for posting about this, saved me a lot of hours (and trouble)...

^_^y

Like others I can confirm that using the following code works when trying to Scaffold using the code generator:

bool isAdmin = false;
 bool.TryParse(userInfo[5], out isAdmin);

Following code doesnt:
bool.TryParse(userInfo[5], out bool isAdmin);

I had to undo all the changes I made to match the vs2017 suggestions.

Can confirm the answer davec21 posted. You need to change ALL unsupported code, not just the classes you actually want to scaffold.

Closing this issue as this has been fixed for 2.0.0-preview1 version, and currently there is no way to support scaffolding in this scenario for 1.0 and 1.1 versions.

cc @mlorbetske

currently there is no way to support scaffolding in this scenario for 1.0 and 1.1 versions.

Update:

There is a workaround to let scaffolding in versions 1.0 and 1.1 work with C#7 code.

  • Install (or update) NuGet package Microsoft.CodeAnalysis.CSharp.Workspaces version 2.0.0 or higher to the project.
  • Restore and retry scaffolding.

This is the craziest thing. I had the same problem as described above and attempted to follow the solution commented on by @davec21, but I only found one instance where my application was using an "out" variable. Strangely enough, this one instance has nothing to do with the model on which I was attempting to scaffold.

Once I added a predefined variable prior to the "out" part that assigns a value to that variable, I was able to successfully scaffold the other models I wanted to scaffold.

Here is my pre-edit code:

if (!_memoryCache.TryGetValue("Tutorials", out tutorials))
{
     tutorials = null;
}
return tutorials;

This was my edit:

List<Tutorial> tutorials = new List<Models.Tutorial>();
if (!_memoryCache.TryGetValue("Tutorials", out tutorials))
{
     tutorials = null;
}
return tutorials;

Thank you all for your help.

Same problem for scaffolding controllers or views with asp.net core 2.0 and VS 20117 15.3, and without specific C#7 code. I am unable to determine from which step the problem appeared. I tried to remvove the last classes I added, but without success...

Thanks @prafullbhosale - Installing package Microsoft.CodeAnalysis.CSharp.Workspaces (latest: 2.2.4) worked like a charm!

Installing package Microsoft.CodeAnalysis.CSharp.Workspaces worked, thank you!

If I have a "Pages" folder in my MVC project then no scaffolding works. so i just deleted it and all worked fine after.

Was this page helpful?
0 / 5 - 0 ratings