Thursday 2 July 2020

EntityFramework Insert error due to PrimaryKey



MyProject.Controllers.CurrencyCodesController Unable to update the EntitySet 'CurrencyCodes' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
System.Data.Entity.Infrastructure.DbUpdateException: Unable to update the EntitySet 'CurrencyCodes' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation. ---> System.Data.Entity.Core.UpdateException: Unable to update the EntitySet 'CurrencyCodes' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.


Scenario: 
The error occured while trying to insert the currencycodes entity to the database. 
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "cucCurrencyCode,cucDescription,cucMultiplier,cucRate,cucInUse")] CurrencyCode currencyCode)
{ if (ModelState.IsValid)
{ try
{ db.CurrencyCodes.Add(currencyCode);
db.SaveChanges();
}
 catch (Exception ex) {
log.Error(ex.Message, ex);
}
 return RedirectToAction("Index");
} return View(currencyCode);

}



Solution: 
1) Check Primary key in .edmx file.  In my case cucInUse was set as Entity key. I removed it.
2) Now Right click the .edmx file and click "Open with...". Select XML (text) Editor
3)  Find the element <EntitySet name = "CurrencyCodes"...>
4) Change store:Schema="dbo" => Schema="dbo"
5) delete element <DefiningQuery>
6) Clean the project. 
7) close Visual studio.
8) Open visual studio. Open the project. 
9) Clean and build the project. 
10) Run the application.

No comments:

Post a Comment

Generate SQL script from entity framework using powershell/visual studio

to run the below command , start PowerShell in visual studio. Select the database project. In PowerShell:   Script-Migration this command wi...