c# - If I'm using Guid Identity Web Api 2 It gives me an error -


so here exmaple: model:

[table("items")] public class item {     [key]     [databasegenerated(databasegeneratedoption.identity)]     public guid id { get; set; }     [required]     public string name { get; set; } } 

and 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 receive error, if use string , guid.newguid().tostring(); works fine, there no problem develop app in way want understand problem, using guid works on mvc5.

because of using guid id type, can't defined property identity, remove annotation above id:

[databasegenerated(databasegeneratedoption.identity)]

and add guid.newguid() in constructor of model:

[table("items")] public class item {     public item(){       id=guid.newguid();     }      [key]     public guid id { get; set; }     [required]     public string name { get; set; } } 

and don't set id guid.newguid(), make new object of class.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -