c#


System.Data.Entity.Infrastructure.DbUpdateException error even when i am not updating the id column


I am working on a project where I am using Entity framework to manipulate a DB on sql server 2014.
My code is the following:
private void BtnAddUser(object sender, EventArgs e)
{
var u = new User();
u.username = txtBoxNewUser.Text;
u.password = txtBoxNewPass.Text;
u.rank = cmbBoxRank.GetItemText(this.cmbBoxRank.SelectedItem);
using (var db = new ProjetPooEntities2())
{
db.Users.Add(u);
db.SaveChanges();
}
}
Please note that the code runs perfectly but it when i press the Add button to add the created user to the db an error shows on "db.saveChanges()" and it says:
System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'
And the inner exception is:
SqlException: Cannot insert explicit value for identity column in table 'User' when IDENTITY_INSERT is set to OFF.
I have set the identity column in the db to "id" and it is set to auto-increment by 1 starting from 1.
I have tried searching a lot for a solution but i found nothing.
Any help will be appreciated!!
Suppose the User entity has this structure:
public class User
{
public int id { get; set; }
public string username { get; set; }
public string password { get; set; }
public string rank { get; set; }
}
If Code First is used, add DatabaseGeneratedAttribute with option DatabaseGeneratedOption.Identity as this to set id as identity autoincrement property:
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
... // other properties
}
However if Database First is used, open EDMX model designer, use "Properties" context menu on id field and set StoreGeneratedPattern to Identity:
Then, open EDMX file with XML editor and ensure it has StoreGeneratedPattern="Identity" on id property as shown below:
<EntityType Name="User">
<Key>
<PropertyRef Name="id" />
</Key>
<Property Name="id" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
</EntityType>
If those ways above still won't work thereafter, you can execute SET IDENTITY_INSERT query in DbContext as this (must be reverting with StoreGeneratedPattern="None" in EDMX or DatabaseGenerated(DatabaseGeneratedOption.None) in Code First to work properly):
using (var db = new ProjetPooEntities2())
{
// taken from /a/31856991
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] ON");
db.Users.Add(u);
db.SaveChanges();
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] OFF");
}
Note that this bottom-most approach here considered not a good practice, since it is possible to allow insertion of duplicate values in certain cases.
Related issues:
Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF
How can I force entity framework to insert identity columns?
Try this:
SET IDENTITY_INSERT sometableWithIdentity ON

Related Links

Entity Framework 6 database migrations for isolated multi-tenant setup
File upload / did I make a mistake choosing vb.net instead of php?
Find data in database
Calling sharepoint from web service
Baidu web search engine API
Searching for records on one exact day
Must declare the scalar variable “#ID” for insert parameter
How to get an Image from facebook and use ImageResizer MVC4 & C#
Launch another application [duplicate]
WriteAllLines arguments give an overload error
Calling a C# DLL from C; linking problems
Does C# application made in windows 7 will run in windows xp [closed]
String was not recognized as a valid boolean on sorting
ILMerge : predefined type defined in multiples assemblies
How to query if a website has SSL certificate?
RegEx to find if a string lies in a range of number strings

Categories

HOME
azure-active-directory
locale
microcontroller
window.open
reference
cryengine
crash
localhost
mediarecorder
angularjs-directive
glympse
collision-detection
meson-build
scapy
android-webview
restheart
webpack-dev-server
jpql
point-of-sale
adroitlogic
email-attachments
tracking
element
logstash-configuration
box2d
google-closure-compiler
multibinding
taxonomy
loader
connectiq
opengraph
knapsack-problem
large-files
dynamics-ax-2012-r3
ds-5
selenium3
multilanguage
restler
machine-code
bootcamp
queryover
flume-ng
head
jenkins-2
remap
extjs3
riemann
px4
htop
selection-sort
business-catalyst
nls
stripes
boost-range
konakart
csc
recurring
hfp
db2-zos
methodology
lytro
bootstrap-tabs
syncano
xml-simple
targetprocess
data-representation
douglas-peucker
teamstudio-unplugged
qxorm
formbuilder
system.net
rpt
reactjs-native
smartxls
pidgin
iwork
xml-validation
randomaccessfile
8-puzzle
mobile-robots
sygic
playing-cards
mysql2
magicsuggest
servicemanager
string-length
phone-state-listener
moonscript
shapado
pdf-reader
diazo
facebook-winjs-sdk
nsundomanager
flexbuilder
peoplepicker
jquery-click-event
gmagick
lightopenid
jqtransform
moss2007-security
text-manipulation
activescaffold
database-agnostic
for-xml
versions
lts
qlibrary
weak-typing

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App