skylake skylake - 1 year ago 150
SQL Question

(database first) uniqueidentifier and MVC = duplicate key value

I created an user table in Sql server Management that include primary key Id(

), Name and so on.. I used Entity Framework(database first) to access my database. Everything looked good and I could list data(if I had any).

I created a controller/view for a "Create" page to add new user. Creating a user for the first time worked well, but I couldn't add any more since I got this following order:

Violation of PRIMARY KEY constraint 'PK_User'. Cannot insert duplicate
key in object 'dbo.User'. The duplicate key value is
(00000000-0000-0000-0000-000000000000). The statement has been

As I understand, uniqueidentifier should generate a new and unique guid id every time. This following code is basically just what I wrote, and simply added View.

public class UserController : Controller {

UserEntities db = new UserEntities();

public ActionResult Index() {

return View(db.Users.ToList());

public ActionResult Create() {
return View();

public ActionResult Create(User user) {
if (ModelState.IsValid) {

return RedirectToAction("Index");
return View(user);

This is auto generated code(database first)

namespace User
using System;
using System.Collections.Generic;

public partial class User
public System.Guid Id { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }

Any help would be much appreciated.

Answer Source

You are inserting another user with the same ID. You can do one of the following:

You can use a constraint in your model. Doing so your ModelState won't be valid and the data won't be stored.

You can also check the values you are sending via POST from your form in order to see if you are sending an Id value from the form.

Another possible solution can be trying to auto-increment the primary key value. Try adding this to your model:

public Guid guId { get; set; }

UPDATED: Another possible solution:

  1. Open your edmx file.
  2. Right click -> Model Browser
  3. Right click the Guid column -> Properties -> change the StoreGeneratedPattern to Identity.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download