The Acumen software design blog provides you with helpful articles about Entity Framework.

Several web sites provide a good overview.

Official Microsoft Entity Framework Introduction

Entity Framework Wikipedia

MVC Entity Framework error / EF Error

EF Error




From a page in IIS or a debug session in Visual Studio, you receive the following error:

The associated metadata type for type contains the following unknown properties or fields:

Please make sure that the names of these members match the names of the properties on the main type

Root Cause

The MetadataGenerator.cs file has references to out-of-date relationships.


Rebuild or edit the MetadataGenerator.cs file.  Since MetadataGenerator.cs is an autogenerated file.

Be careful that you don’t lose custom DataAnnotations that you have made for UI and client-side error handling.

For more information about Acumen Software Design, contact us today!

To learn more about Visual Studio, click on the link below:

Entity Framework


In a project using Entity Framework, I received the error:

Error 111: Properties referred by the principal role MyTable must be exactly identical to the key of the entitytype when you compile the project in Visual Studio.

Entity Framework Resolution

I had two existing tables in the edmx diagram.

To create a relationship:

I had to make my identity field a primary key.  I then added the relationship.

In the entity framework diagram, I deleted and re-added the foreign table.

However, I did not delete/re-add the table with the new primary key.

Then, re-add the foreign table.

Next, Visual Studio added the relationship.  The problem is that it builds a relationship to a table that thought did not have a primary key.

When I deleted/re-added the primary key table from the diagram, the error resolved.


For more information on how Acumen can help you, contact us today!

For additional help, contact Microsoft Support by clicking on the link below:

Visual Studio, Entity Framework (EF)

Visual Studio, Entity Framework or EF 4.5

EF error 6.0

Visual Studio 2013


Object reference not set to an instance of an object.

An exception of type ‘System.NullReferenceException’ occurred

Web page error:

System.NullReferenceException was unhandled by user code

Message=Object reference not set to an instance of an object.



at System.Data.EntityKey.AddHashValue(Int32 hashCode, Object keyValue)


The IQueryable query string is valid and returns results, but EF throws and exception anyway when you call ToList().

You can copy the query to SQL Server Management Studio and execute the query successfully.

This can occur if one of your class variables of type “string” has a null value in the query response.

For more information about how Acumen can help with your other Software needs, contact us today!

For additional help, feel free to click on Microsoft’s Support page below:

Recently, while trying to implement Bootstrap’s typeahead.js to an ASP.NET MVC project, we ran into a couple problems. To start, we were using the following articles as a guide:—key-value-pairs/88

The code within these articles worked just fine for the purpose of dealing with in-memory data. For instance, creating a handmade List<Company> would execute without flaws. However, these articles didn’t work for our particular situation because we were dealing with an Entity Framework generated class containing data from a database. This being the case, we figured we could make an equivalent list using an Entity Framework query like so:

var companies = db.Companies.Where(m => m.Name.StartsWith(query)).Select(c => new { c.Name, c.CompanyID });

This turned out to be only half of the battle. We were still having issues so we began logging some JavaScript objects in the console. With the handmade list, the console showed a conventional JSON object. On the other hand, when we passed the Entity Framework JSON serialized object we got numerous errors, including:

A circular reference was detected while serializing an object of type ‘System.Data.Entity.DynamicProxies.Company_983FFFBF6539DF8F813E1EAB1A1565F8743CF808D3B09F748B8A4906B756C4EF’.

We tried manually serializing, but it gave a similar error:

Using JsonConvert.SerializeObject
In Visual Studio before getting to client:
Self referencing loop detected for property ‘Company’ with type ‘System.Data.Entity.DynamicProxies.Company_983FFFBF6539DF8F813E1EAB1A1565F8743CF808D3B09F748B8A4906B756C4EF’. Path ‘[0].SalesCalls[0]’.

So, the big problem was trying to serialize an Entity Framework object. This can be done by changing a particular setting to false. In your code, you can simply call the following:

context.Configuration.ProxyCreationEnabled = false;

After adding that, we had no more issues. Our final action method looked like this:

public ActionResult GetCompanies(string query) {

    // Enable json serialization of the object.
    db.Configuration.ProxyCreationEnabled = false;

    var companies = db.Companies.Where(m => m.Name.StartsWith(query)).Select(c => new { c.Name, c.CompanyID });

    return Json(companies, JsonRequestBehavior.AllowGet);

Recently, while developing an application using Entity Framework, I ran into several compilation errors after adding an additional table to my database. Most notably was this error when trying to declare a couple of variables that had once worked before:

Compiler Error Message: CS1061: … does not contain a definition for … and no extension method … accepting a first argument of type … could be found (are you missing a using directive or an assembly reference?)

When searching around in my .edmx file for reasons as to why my relationships were not working, I ran into this message under the mapping details:

“Mappings are not allowed for an association over exposed foreign keys.”

I wanted to note that this message is not relevant to the issue at hand. After I solved the problem, I still received this message.

I quickly realized that the error had to do with the relationships between tables that I had previously established. When I had added the new table, I deleted the diagram from my .edmx file and updated the model from the database like I normally do when adding a new table. However, this time, Entity Framework did not properly regenerate the code associated with my database. Each property was stored as a class member within the entity class as expected, but my relationships were not. This was despite the fact that my .edmx diagram showed the relationships exactly as they should be.

After hours of Googling different phrases and errors, I ran into this ticket

As it turns out, this is a bug with Entity Framework inside of VS2012, and if your Visual Studio is out of date, you are likely to experience it. Because of this bug, if your .edmx file is nested within a project folder, Entity Framework will sometimes fail to generate code properly. Fortunately, the solution is much easier to implement than it is to find. You can do any of the following:

  • Update your Visual Studios here
  • Right click on the .tt file and select “Run Custom Tool”.
  • Drag the .edmx file out of the project folder.

Recently, I tried to build an MVC4 application using the SimpleMembershipProvider offered by the Internet Application template. Unfortunately I ran into a slew of compiling errors, run-time errors, and database connection errors once I added in my Entity Framework entities. After tracing down all the issues, I was able to get a clean-slate solution with the SimpleMembershipProvider and Entity Framework working side-by-side in MVC4. Assumptions

  1. EntityFramework has been installed.
  2. The SimpleMembershipProvider files are in the project correctly. Such as…
    1. InitializeSimpleMembershipAttribute.cs
    2. AccountController.cs
    3. AccountModels.cs

Database Setup First, make sure your table has a UserProfile table set up using the following script. Once this is set up, the membership provider will do the rest of the legwork (creating the rest of the tables it needs) for you. Kerrry1

/****** Object:  Table [dbo].[UserProfile]    Script Date: 9/20/2013 10:24:48 AM ******/



CREATE TABLE [dbo].[UserProfile](
	[UserId] [int] IDENTITY(1,1) NOT NULL,
	[UserName] [varchar](75) NOT NULL,
	[UserId] ASC



Note: If you do not set the UserId as the primary key, you can get errors like this:

  1. The ASP.NET Simple Membership database could not be initialized. For more information, please see

Delete the UsersContext and Code-First Models

We will no longer need the UsersContext when we have our Entity Framework context created, so we can just remove it. We also want to remove the UserProfile code-first class to avoid errors such as #1 (Missing partial modifier on declaration of type ‘MvcApplication1.Models.UserProfile’; another partial declaration of this type exists). Kerry2

Creating the Entities and Connection String

Now, add your new entities through EntityFramework through the Add -> ADO.NET Entity Data Model wizard (IMAGE This will create the class files for your objects as well as generate a new connection string into the Web.config with which EntityFramework uses to create a context.

Setting SimpleMembershipProvider’s Context

If you try to build, you will get some errors such as “The type or namespace name ‘UsersContext’ could not be found (are you missing a using directive or an assembly reference?)”. Track all of these down and replace UsersContext with the name of your database context (“MyEntitiesContext” or whatever you named it). There will be 2 uses in Controllers/AccountController.cs and 2 uses in Filters/InitializeSimpleMembershipAttribute.cs.

Modifying the DefaultConnection String

The DefaultConnection string is the one used by the SimpleMembershipInitializer. You can change the name of this on (by default) line 33 of Filters/InitializeSimpleMembershipAttribute.cs: WebSecurity.InitializeDatabaseConnection(“DefaultConnection”, “UserProfile”, “UserId”, “UserName”, autoCreateTables: true); Kerry3 NOTE: You cannot use the same connection string as the Entity Framework connection string. If you do, you will see errors like this:

  1. The ASP.NET Simple Membership database could not be initialized. For more information, please see

Instead, you need to pull out the “provider connection string” value in the Entity Framework connection string, without the “App=EntityFramework” parameter. For example:

    <add name="DefaultConnection" connectionString="data source=(local);initial catalog=actest;user id=sa;password=[mypassord];MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
    <add name="MyEntities" connectionString="metadata=res://*/Models.Entities1.csdl|res://*/Models.Entities1.ssdl|res://*/Models.Entities1.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=actest;user id=sa;password=[mypassword];MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

You are now free to use Entity Framework! You can download the source code at my GitHub repository. Bonus note: To resolve this error, add a primary key to your entity and re-generate the model. Unable to update the EntitySet [your_entity] because it has a DefiningQuery and no <InsertFunction> element exists in the element to support the current operation. Check out our .NET Development page for more ways we can help you!

In Visual Studio using Entity Framework 5.0, I receive the following error when working with link tables (many-to-many mapping tables):

Error 3034: Problem in mapping fragments starting at lines:Two entities with possibly different keys are mapped to the same row. Ensure these two mapping fragments map both ends of the AssociationSet to the corresponding columns.

First, it really helps to clearly understand how Entity Framework handles many to many mapping tables.  If a linking table has any fields other than the two linking ID fields, it will cause Entity Framework some trouble, but doesn’t cause this error.  It is also important to specify the foreign keys so Entity Framework knows what the fields are for.  For great detail, see

After a lot of searching and manipulation of Primary Keys (PK) and Foreign Keys (FK) I found that no logical action fixed the problem.  Theoretically you could edit the EDMX (XML) file and fix something, but it can be thousands of lines long and very cryptic.  You aren’t supposed to have to edit the EDMX file – certainly not for an error like this.  Again, theoretically you should be able to “Update Model from Database”, but it doesn’t resolve this problem.

Entity Framework Resolution

The resolution that seems to work for many and also worked for me was to delete the EDMX file and rebuild it.  The only warning is that you must specify the same names in the Wizard or your class names won’t match.  It isn’t worth the trouble to try to rename the classes.  If you find that you have changed the class names, you can also delete and rebuild your .tt/.cs files and regenerate them too.  At this point, you should have very few class references that are incorrect.


For information about how Acumen can help with your Software needs, contact us today!