Entity Framework Error on SaveChanges()

Resolving the issue

    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 have been recently facing an issue while saving data in one of the table using Entity Framework. an exception occurred on the line DBEntities.SaveChanges() and it says the following:

Issue:

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

Reason:

After analyzing it a bit, I get to know that the reason for the same is that the concerned table does not have any Primary Key assigned to it. When a table does not have a primary key then the Entity Framework considers it to be a View and not a table and hence it does not allow data to be directly inserted to it.

Resolution:

There are two ways to resolve this issue:

  1. Either define a Primary Key to the table. Doing this the Entity Framework would start considering it as a table and not a View and the issue will be resolved. Although this might not be the requirement in the first place so for that you can consider the next resolution.

  2. You would have to manually make some changes to the EDMX file by the following the below steps:

    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 tag entirely.
    4. Rename the store:Schema="dbo" to Schema="dbo" (otherwise, the code will generate an error saying the name is invalid).

After doing this, the Entity Framework would now allow saving data to the concerned table.

Please feel free to comment your ideas as well.