Reputation: 4325
So here is my Exmaple: Model:
[Table("Items")]
public class Item
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
}
And my Web Api 2 Controller Part:
// POST: api/Items
[ResponseType(typeof(Item))]
public async Task<IHttpActionResult> PostItem(Item item)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
item.Id = Guid.NewGuid();
db.Items.Add(item);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = item.Id }, item);
}
On insert I receive an error, but if I use string and Guid.NewGuid().Tostring();
everything works fine, there is no problem to develop my App in this way but I want understand what is the problem, using GUID like this works on MVC5.
Upvotes: 0
Views: 734
Reputation: 588
Because of using Guid
as your Id type, It can't be defined to be an property identity, so
remove this annotation above your Id:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
and add Guid.NewGuid()
in constructor of your model:
[Table("Items")]
public class Item
{
public Item(){
Id=Guid.NewGuid();
}
[Key]
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
}
And then don't set your Id to Guid.NewGuid()
, just make a new object of your class.
Upvotes: 2