I am using Entity Framework 1 with .net 3.5.

I am doing something simple like this:

var roomDetails = context.Rooms.ToList();

foreach (var room in roomDetails)
   room.LastUpdated = DateTime.Now;

I am getting this error when I try to do:


I get the error:

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.

I am doing lots of updates on the context and not having any issues, it's only when I try to update this particular entity.

All my searching shows up the same thing, that there is no primary key declared on the entity that I'm trying to update. But alas, I do have a Primary key declared...

  • 9,204
  • 10
  • 63
  • 89
  • 9,151
  • 14
  • 57
  • 84

22 Answers22


It usually happens because one of the following reasons:

  • Entity Set is mapped from Database view
  • A custom Database query
  • Database table doesn't have a primary key

After doing so, you may still need to update in the Entity Framework designer (or alternatively delete the entity and then add it) before you stop getting the error.

Vijay Chavda
  • 826
  • 2
  • 15
  • 34
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • 3
    Make sure to also change store:Schema to just Schema for that EntitySet, if you're still having troubles. – Geoff Oct 04 '12 at 14:33
  • So, the solution is to add a primary key then? – Vivian River Nov 19 '12 at 22:11
  • 56
    Then delete and recreate the entity because update doesn't work right in the EF designer. – Suncat2000 Feb 28 '13 at 13:22
  • 1
    Update in the EF designer worked fine for me after adding Primary Key to database. Using EF 5.0 and .net 4.0 – StillLearnin Jul 29 '13 at 14:47
  • 1
    Same here ! Thx ... had to remove table and re add to EF to get it to take though – ajzeffer Mar 20 '14 at 18:52
  • 1
    What if you cannot add an primary key – eugenekgn Mar 21 '14 at 15:33
  • Migrated the data to antoher DB. And forgot to maintain the key. This answer was the solution (created a script to reproduce the key) – J.Olsson Apr 10 '15 at 08:04
  • I am using a view and have an instead of trigger on it. is there anyway I can use the view through EF to insert, update and delete?
    Edit: I made use of [this](http://stackoverflow.com/questions/11974384/ef-code-first-and-database-views) answer of your. @LadislavMrnka
    – Talal Yousif May 19 '15 at 13:04
  • My table was missing Primary key. I updated the table and it started working – Raj Chaurasia Oct 26 '15 at 17:23
  • I was having the same issue. I didn't have any PK column in database, and when i added model, it set two columns as entity key. Later i set PK but forget to update the model. I just update the model and everything was fine – Atta H. Aug 26 '16 at 19:51
  • Added PK in SSMS, opened model in VS, updated from database, ran custom tool on .tt files, rebuild solution, works now - that's the steps I followed for success. – qxotk Nov 18 '16 at 22:59
  • PK was the problem here too, it had been added to the DB but wasn't in the model. Update didn't work, but removing and readding the entity did, as suggested above. – Dan Jan 17 '17 at 14:05
  • Add primary key and don't forget to update your Entity Framework model afterwards – theTechRebel Jan 15 '18 at 16:09
  • A primary key was needed for the table. Also needed to update model from database on the .edmx file for my EF connection. – SouravOrii Jun 06 '18 at 10:32
  • Also worth noting the column must be set to be an identity column, not only a primary key – GregH Dec 03 '18 at 19:28
  • On mine case was Database table doesn't have a primary key – AlejandroDG Feb 06 '19 at 14:18

Just Add a primary key to the table. That's it. Problem solved.

Jebastin J
  • 1,251
  • 1
  • 10
  • 10

This is the case for me. Simply removing resulted in another error. I followed the steps of this post except the last one. For your convenience, I copied the 4 steps from the post that I followed to solve the problem as following:

  1. Right click on the edmx file, select Open with, XML editor
  2. Locate the entity in the edmx:StorageModels element
  3. Remove the DefiningQuery entirely
  4. Rename the store:Schema="dbo" to Schema="dbo" (otherwise, the code will generate an error saying the name is invalid)
  • 4,910
  • 3
  • 37
  • 46
kavitha Reddy
  • 3,303
  • 24
  • 14
  • Thank you very much - this is exactly what fixed my problem. Pretty disturbing that this hasn't been fixed in EF. And, pretty amazing that you figured this out! – Bicycle Dave Apr 02 '16 at 01:12
  • I tried deleting the entity and re-adding it. Recompiling. Cleaning. Nothing worked for me except this. – vintastic May 12 '16 at 16:21
  • 1
    This solved my issue yet I don't know how you came up with answers and why your suggestion solved the issue. – swcraft Dec 28 '16 at 23:03
  • What happens if you need to update the database model? I did an "Update Model from Database" and it left my model totally unusable. I had to undo and start over again. If there a way around this? – Gary Sep 13 '17 at 20:02
  • That's a really weird issue. Is there any information on how this problem occurs in order to avoid it? Nonetheless - it helped – r3dst0rm Jan 24 '18 at 09:56
  • Thanks for the save for the second time! I completely forgot this fix, if I could up vote again I would – Luke Duddridge Jul 31 '18 at 09:00
  • Worked for me, thanks. I had a joining table with two primary keys and using database first. Viewing the XML of the edmx there was an error commented above the joining table definition. Removing the DefiningQuery as described fixed the problem. – Richard Moore Sep 16 '22 at 17:38

Just note that maybe your Entity have primary key but your table in database doesn't have primary key.

  • 13,853
  • 15
  • 77
  • 113

UPDATE: I've gotten a few upvotes on this lately, so I figured I'd let people know the advice I give below isn't the best. Since I originally started mucking about with doing Entity Framework on old keyless databases, I've come to realize that the best thing you can do BY FAR is do it by reverse code-first. There are a few good articles out there on how to do this. Just follow them, and then when you want to add a key to it, use data annotations to "fake" the key.

For instance, let's say I know my table Orders, while it doesn't have a primary key, is assured to only ever have one order number per customer. Since those are the first two columns on the table, I'd set up the code first classes to look like this:

    [Key, Column(Order = 0)]
    public Int32? OrderNumber { get; set; }

    [Key, Column(Order = 1)]
    public String Customer { get; set; }

By doing this, you're basically faked EF into believing that there's a clustered key composed of OrderNumber and Customer. This will allow you to do inserts, updates, etc on your keyless table.

If you're not too familiar with doing reverse Code First, go and find a good tutorial on Entity Framework Code First. Then go find one on Reverse Code First (which is doing Code First with an existing database). Then just come back here and look at my key advice again. :)

Original Answer:

First: as others have said, the best option is to add a primary key to the table. Full stop. If you can do this, read no further.

But if you can't, or just hate yourself, there's a way to do it without the primary key.

In my case, I was working with a legacy system (originally flat files on a AS400 ported to Access and then ported to T-SQL). So I had to find a way. This is my solution. The following worked for me using Entity Framework 6.0 (the latest on NuGet as of this writing).

  1. Right-click on your .edmx file in the Solution Explorer. Choose "Open With..." and then select "XML (Text) Editor". We're going to be hand-editing the auto-generated code here.

  2. Look for a line like this:
    <EntitySet Name="table_name" EntityType="MyModel.Store.table_name" store:Type="Tables" store:Schema="dbo" store:Name="table_nane">

  3. Remove store:Name="table_name" from the end.

  4. Change store:Schema="whatever" to Schema="whatever"

  5. Look below that line and find the <DefiningQuery> tag. It will have a big ol' select statement in it. Remove the tag and it's contents.

  6. Now your line should look something like this:
    <EntitySet Name="table_name" EntityType="MyModel.Store.table_name" store:Type="Tables" Schema="dbo" />

  7. We have something else to change. Go through your file and find this:
    <EntityType Name="table_name">

  8. Nearby you'll probably see some commented text warning you that it didn't have a primary key identified, so the key has been inferred and the definition is a read-only table/view. You can leave it or delete it. I deleted it.

  9. Below is the <Key> tag. This is what Entity Framework is going to use to do insert/update/deletes. SO MAKE SURE YOU DO THIS RIGHT. The property (or properties) in that tag need to indicate a uniquely identifiable row. For instance, let's say I know my table orders, while it doesn't have a primary key, is assured to only ever have one order number per customer.

So mine looks like:

<EntityType Name="table_name">
                <PropertyRef Name="order_numbers" />
                <PropertyRef Name="customer_name" />

Seriously, don't do this wrong. Let's say that even though there should never be duplicates, somehow two rows get into my system with the same order number and customer name. Whooops! That's what I get for not using a key! So I use Entity Framework to delete one. Because I know the duplicate is the only order put in today, I do this:

var duplicateOrder = myModel.orders.First(x => x.order_date == DateTime.Today);

Guess what? I just deleted both the duplicate AND the original! That's because I told Entity Framework that order_number/cutomer_name was my primary key. So when I told it to remove duplicateOrder, what it did in the background was something like:

WHERE order_number = (duplicateOrder's order number)
AND customer_name = (duplicateOrder's customer name)

And with that warning... you should now be good to go!

  • 9,796
  • 3
  • 35
  • 59
  • Found this answer after finding the same solution to the problem. Definitely the correct answer! Only defining a primary key like mentioned in other answers won't help in many cases. – Obl Tobl Nov 18 '14 at 09:44

This can also happen if data model is out of date.

Hopefully this will save someone else frustration :)

  • 945
  • 1
  • 9
  • 29

The error may have occurred if your table doesn't have a primary key, in this case the table is "read only", and the db.SaveChanges () command will always error.

  • 2,707
  • 5
  • 31
  • 36
  • 376
  • 3
  • 11

I was getting the same error message, but in my scenario I was trying to update entities derived from a many-to-many relationship using a PJT (Pure Join Table).

From reading the other posts, I thought I could fix it by adding an additional PK field to the join table... However, if you add a PK column to a join table, it is no longer a PJT and you lose all of the entity framework advantages like the automatic relationship mapping between the entities.

So the solution in my case was to alter the join table on the DB to make a PK that includes BOTH of the foreign ID columns.

Kerry Randolph
  • 591
  • 6
  • 15
  • Is this how generating EDMX has always worked? I'm used to working with Code First which doesn't require a PK on a pure join table. – Michael Hornfeck Oct 30 '14 at 16:46

Set Primary Key then save Table and Refresh then go to Model.edmx delete Table and get again .

Ali Raza
  • 79
  • 1
  • 4

so its true, just add a primary key

Note: be sure that when you're updating your EF diagram from the database that you're pointing to the right database, in my case the connection string was pointing to a local DB instead of the up-to-date Dev DB, schoolboy error i know, but I wanted to post this because it can be very frustrating if you're convinced you've added the primary key and you're still getting the same error

  • 3,784
  • 3
  • 26
  • 15

enter image description here

In my case, forgot to define Primary Key to Table. So assign like shown in Picture and Refresh your table from "Update model from Database" from .edmx file. Hope it will help !!!

Yogesh Dangre
  • 181
  • 1
  • 4

I had the same issue. As this thread said, My table didn't have a PK, so I set the PK and ran the code. But unfortunately error came again. What I did next was, deleted the DB connection (delete .edmx file in Model folder of Solution Explorer) and recreated it. Error gone after that. Thanks everyone for sharing your experiences. It save lots of time.

  • 31
  • 1

This is not a new answer but will help somebody who's not sure how to set primary key for their table. Use this in a new query and run. This will set UniqueID column as primary key.

USE [YourDatabaseName]

Alter table  [dbo].[YourTableNname]
Add Constraint PK_YourTableName_UniqueID Primary Key Clustered (UniqueID);
  • 73
  • 1
  • 7

I was getting this issue because i was generating my EDMX from an existing database (designed by somebody else, and i use the term 'designed' loosely here).

Turns out the table had no keys whatsoever. EF was generating the model with many multiple keys. I had to go add a primary key to the db table in SQL and then updated my model in VS.

That fixed it for me.

  • 444
  • 5
  • 15

Adding the primary key worked for me too !

Once that is done, here's how to update the data model without deleting it -

Right click on the edmx Entity designer page and 'Update Model from Database'.

Abhishek Poojary
  • 749
  • 9
  • 10

I had the exact same problem, unfortunately, adding the primary key doesn't solve the issue. So here's how I solve mine:

  1. Make sure you have a primary key on the table so I alter my table and add a primary key.
  2. Delete the ADO.NET Entity Data Model (edmx file) where I use to map and connect with my database.
  3. Add again a new file of ADO.NET Entity Data Model to connect with my database and for mapping my model properties.
  4. Clean and rebuild the solution.

Problem solved.

Willy David Jr
  • 8,604
  • 6
  • 46
  • 57

just add a primary key to your table and then recreate your EF

  • 440
  • 5
  • 14

I just had to remove the table from the model and update the model again bringing the table back. I guess the primary key was created after the table was pulled into the model.

  • 6,398
  • 4
  • 27
  • 37

I had this issue come up and believe it was caused because I had deleted the Index on my tables primary key and replaced it with an index on some of the other fields in the table.

After I deleted the primary key index and refreshed the edmx, inserts stopped working.

I refreshed the table to the older version, refreshed the edmx and everything works again.

I should note that when I opened the EDMX to troubleshoot this issue, checking to see if there was a primary key defined, there was. So none of the above suggestions were helping me. But refreshing the index on the primary key seemed to work.

  • 623
  • 8
  • 11

Open Your .edmx file in XML editor and then remove tag from Tag and also change store:Schema="dbo" to Schema="dbo" and rebuild the solution now error will resolve and you will be able to save the data.


I found the original answer of updating the .edmx file work best in my situation. I just wasn't too happy about altering the model every time it was updated from the database. That's why I wrote an additional Text Template file, that is automaticaly invoked when after the model has changed - just like the entities are newly generated. I post it here in this comment. To make it work, make sure you name it like {model name}.something.tt, and store it in the same folder as your .edmx folder. I named it {model name}.NonPkTables.tt. It does not generate a file on its own due to the invalid file extension definition in the second line. Feel free to use.

<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ output extension="/" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq"#>
<#@ assembly name="%VS120COMNTOOLS%..\IDE\EntityFramework.dll" #>
<#@ assembly name="%VS120COMNTOOLS%..\IDE\Microsoft.Data.Entity.Design.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Windows.Forms" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="System.Globalization" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.Data.Entity.Core.Metadata.Edm" #>
<#@ import namespace="System.Data.Entity.Core.Mapping" #>
<#@ import namespace="System.CodeDom" #>
<#@ import namespace="System.CodeDom.Compiler" #>
<#@ import namespace="Microsoft.CSharp"#>
<#@ import namespace="System.Text"#>
<#@ import namespace="System.Diagnostics" #>

    string modelFileName= this.Host.TemplateFile.Split('.')[0] + ".edmx";
    string edmxPath = this.Host.ResolvePath( modelFileName );

    // MessageBox.Show( this.Host.TemplateFile + " applied." );
    var modelDoc = XDocument.Load(edmxPath);
    var root = modelDoc.Root;
    XNamespace nsEdmx = @"http://schemas.microsoft.com/ado/2009/11/edmx";
    XNamespace ns = @"http://schemas.microsoft.com/ado/2009/11/edm/ssdl";

    var runtime = root.Elements(nsEdmx + "Runtime").First();
    var storageModels = runtime.Elements(nsEdmx + "StorageModels").First();
    XNamespace nsStore = @"http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator";

    var schema = storageModels.Elements(ns + "Schema").First();
    XNamespace nsCustomAnnotation = @"http://schemas.microsoft.com/ado/2013/11/edm/customannotation";

    var entityTypes = schema.Nodes().OfType<XComment>().Where(c => c.Value.Contains("warning 6002: The table/view"));
    bool changed = false;

    foreach (var node in entityTypes)
        var element = node.ElementsAfterSelf().First();
        string entityName = element.Attribute("Name").Value;

        // Find EntitySet in EntityContainer.
        var entityContainer = schema.Elements(ns + "EntityContainer").First();
        var entitySet = entityContainer.Elements(ns + "EntitySet").First(s => s.Attribute("Name").Value == entityName);

        // Change "store:Schema" attribute to "Schema" attribute.
        var attribute = entitySet.Attribute(nsStore + "Schema");

        if (attribute != null)
            string schemaName = entitySet.Attribute(nsStore + "Schema").Value;
            entitySet.Attribute(nsStore + "Schema").Remove();
            entitySet.Add(new XAttribute("Schema", schemaName));
            changed |= true;

        // Remove the DefiningQuery element.
        var definingQuery = entitySet.Element(ns + "DefiningQuery");

        if (definingQuery != null)
            changed |= true;        
            Debug.WriteLine(string.Format("Removed defining query of EntitySet {0}.", entityName));

    if (changed)

I fixed it by just deleting and rebuilding the EF project and all its classes. See details below:

I went round and round on this one for an hour, then deleted the EF project containing the error, saving out all my custom code, then rebuilding the whole thing. Since it was just a matter of generating a new EF diagram and its inner code, this process of fixing the problem took about 10 minutes.

The problem, I suspect, is that the database-first method for generating EF classes and properties gets a little weird after two or three "updates". Basically, I found a problem in the code behavior, went and fixed the database table properties, and then updated the EF diagram one time too many. Then I tried fiddling with the code, which didn't work.

Starting over worked.

  • 3,653
  • 1
  • 22
  • 33