Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate and auto increment Id with Entity Framework

Revised entire post.

I'm trying to post the following JSON POST request via Fiddler:

{Username:"Bob", FirstName:"Foo", LastName:"Bar", Password:"123", Headline:"Tuna"} 

However I'm getting this error:

Message "Cannot insert the value NULL into column 'Id', table 'xxx_f8dc97e46f8b49c2b825439607e89b59.dbo.User'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated." string 

Though if I manually send a random Id along with the request then all is good. Like so:

{Id:"1", Username:"Bob", FirstName:"Foo", LastName:"Bar", Password:"123", Headline:"Tuna"} 

Why does Entity Framework not generate and auto increment the Id's? My POCO class is as follows:

public class User {     [Key]     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]     public string Id { get; set; }     public string Username { get; set; }     public string FirstName { get; set; }     public string LastName { get; set; }     public string Password { get; set; }     public string Headline { get; set; }     public virtual ICollection<Connection> Connections { get; set; }     public virtual ICollection<Address> Addresses { get; set; }     public virtual ICollection<Phonenumber> Phonenumbers { get; set; }     public virtual ICollection<Email> Emails { get; set; }     public virtual ICollection<Position> Positions { get; set; } }  public class Connection {     public string ConnectionId { get; set; }     public int UserId { get; set; }     public virtual User User { get; set; } }  public class Phonenumber {     public string Id { get; set; }     public string Number { get; set; }     public int Cycle { get; set; }     public int UserId { get; set; }     public User User { get; set; } } 

Here is the controller method. When in debug mode and I send the request via Fiddler it breaks at db.SaveChanges(); and gives the error seen a bit above.

    // POST api/xxx/create     [ActionName("create")]     public HttpResponseMessage PostUser(User user)     {         if (ModelState.IsValid)         {             db.Users.Add(user);             db.SaveChanges();              HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);             response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.Id }));             return response;         }         else         {             return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);         }     } 

What's wrong?

Solution

Change string Id to int instead and remove Data annotations. Renamed the Id to UserId, still following convention, and made changes where necessary in other POCO's to match up with the changes.

like image 1000
brk Avatar asked Apr 18 '13 09:04

brk


People also ask

How can I get auto increment ID in SQL Server?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

How do I add an auto increment to an existing column?

To add a new AUTO_INCREMENT integer column named c : ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (c); We indexed c (as a PRIMARY KEY ) because AUTO_INCREMENT columns must be indexed, and we declare c as NOT NULL because primary key columns cannot be NULL .

How do you get the last ID from a table if it's set to auto increment?

To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT. Creating a table, with “id” as auto-increment.

Can Unique Key be set for auto increment?

A unique key does not supports auto increment value. We cannot change or delete values stored in primary keys. We can change unique key values.


2 Answers

This is a guess :)

Is it because the ID is a string? What happens if you change it to int?

I mean:

 public int Id { get; set; } 
like image 65
tymtam Avatar answered Sep 28 '22 01:09

tymtam


You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

like image 34
walther Avatar answered Sep 28 '22 01:09

walther