简体   繁体   中英

WebAPI with Entity Framework, Code First: Doesn't generate correct Id of inserted object

EDIT : Updated post, still need help with this.

Question is Why is is not adding the user with correct ID?

I'm working with WebAPI and whenever I make POST request via Fiddler, it adds an user with the incorrect ID.

I've Entity Framework to auto generate and increment the ID of my POCO class (User) yet instead of adding the user with ID of 1, it now acts if there were users in the database already and just creates the User with ID of for instance 16.

I checked the tables in Visual Studios Server Explore, where I right click the table and choose Show Table Data and there's nothing.

I've tried to clean and rebuild the solution and checked if there was any users in the table but none.

This is my Connection string in the Web.config file:

 <add name="ConnectoDbContext" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=CONNECTO_f8dc97e46f8b49c2b825439607e89b59;Integrated Security=True;AttachDbFilename=|DataDirectory|\Connecto.mdf" />

I used a Code First approach to a new DB.

I've also checked Microsoft SQL Server 2012, SQL Server Management Studio where I see a DB named CWS.Models.ConnectoDbContext so I am assuming that is the same one. However I must admit I have experienced inconsistency, some times it would have old tables even though I didn't have them in my solution anymore.

In SQL Server Management Studio I have checked that the UserId is an Identity Column. In Visual Studio I also checked the UserId column and it says, Is Identity: True .

I did run the following DBCC CHECKIDENT ("[User]", NORESEED); both in Visual Studio and in SQL Server Management Studio.

SQL Server Management Studio returns:

Checking identity information: current identity value 'NULL', current column value 'NULL'. DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Visual Studio returns:

Checking identity information: current identity value '16', current column value 'NULL'. DBCC execution completed. If DBCC printed error messages, contact your system administrator.

They are both returning something different which makes me believe that they're not "connected" as in, it's not the same DB?

Any help would be greatly appreciated

/twice

You'll need to re-seed the identity column:

DBCC CHECKIDENT ("[TableName]", NORESEED);

Be wary of doing this if you have data in there in other instances (could lead to duplicate keys later on).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM