Search code examples
c#asp.net-mvcvisual-studio-2010using

Why is a class recognized in one part of my project, but not in another?


I'm trying to create a modified public version of a private method that appears in a Controller class in the project I'm working on. The private method returns a List of a custom type, whereas in the public method I want to return a List of int.

So, I copied the existing method from the controller class in the \Controllers folder to a new Utils class that I added beneath the App_Code folder.

It turns out, though, that for the code to compile, I need to add certain "using" clauses; no problem?

For example, in this line of code:

get { return int.Parse(CCRCustomer.GetCustomerNumberFromUsername(User.Identity.Name)); }

..."Identity" is red - unrecognized. I think "User" is supposed to be a custom class of ours; but when I hover over it,

it says, "Module System.Data.Entity ... "

Yet adding System.Data.Entity to the using clauses results in the "Entity" portion of that being colored red as unrecognized.

The next problem is this line:

using (var conn = new EntityConnection(ConnectionString))

...in which case it is now "EntityConnection"s turn to be embarrassed and go red/unrecognized.

The controller class which has the original similar code has this:

using System.Data.EntityClient;

...so I thought maybe that's what I needed; but adding that to my Utils class just rewards me with yet more red - on the "Entity" again.

Why would a referenced class be seen from one part of a project, but not from another?


Solution

  • In a web application project, you don't need to add code files to app_code folder; create a regular "Utils" folder in the project and add to it instead. Code files inside app_code compile to a different assembly which is why references to existing project (such is Entity Framework ) are missing for the code you are placing under app_code.

    Edit: To shed more light on this, ASP.NET Mvc by default does not give you a way to add app_code folder. This is because app_code primarily exists for websites in which the code files are compiled dynamically. Web applications are pre-compiled and Mvc comes only as a web application project in Visual Studio. Though as mentioned in the linked SO question, you may workaround this if you really need to.