I cannot generate a new guid id for my primary key. Getting same error every time when I try to create an another user as it wont generate a new guid id.
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 terminated.
Code:
public partial class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
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; }
}
My UserController code
[HttpGet]
public ActionResult Create() {
return View();
}
[HttpPost]
public ActionResult Create(User user) {
if (ModelState.IsValid) {
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
How do I automatically generate new guids?
GUIDs can be considered as global primary keys. Local primary keys are used to uniquely identify records within a table. On the other hand, GUIDs can be used to uniquely identify records across tables, databases, and servers.
DataSource GUID not auto-generated when creating a new record using the Patch function. From the documentation the ID GUID in the source table should be updated automatically when executing the Patch function. The same happens when the uniqueidentifier is not set as a GUID.
The globally unique identifier (GUID) data type in SQL Server is represented by the uniqueidentifier data type, which stores a 16-byte binary value. A GUID is a binary number, and its main use is as an identifier that must be unique in a network that has many computers at many sites.
A GUID can be used to ID hardware, software, accounts, documents and other items. The term is also often used in software created by Microsoft. GUIDs are useful when a unique identifier is needed that has a very low probability of being repeated. The text string can be used across all computers and networks.
Your c# code is not generating any GUID because you are instructing it to do so. Your model says that the value of Id is generated by database (DatabaseGenerated(DatabaseGeneratedOption.Identity)
)
The issue is in your table definition in the database. If you are using SQL server, using SQL server management studio, review your table's definition and make sure that ID is actually defined as 'Identity'
you can do in constructor of class like this
public User()
{
this.Id= Guid.NewGuid();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With