C# 如何使用实体框架生成和自动递增 Id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16079217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate and auto increment Id with Entity Framework
提问by brk
Revisedentire post.
修改了整个帖子。
I'm trying to post the following JSON POST request via Fiddler:
我正在尝试通过 Fiddler 发布以下 JSON POST 请求:
{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 以及请求,那么一切都很好。像这样:
{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:
为什么实体框架不生成并自动增加 Id?我的 POCO 课程如下:
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.
这是控制器方法。在调试模式下,我通过 Fiddler 发送请求时,它会中断db.SaveChanges();并给出上面看到的错误。
// 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.
将字符串 Id 改为 int 并删除数据注释。将 Id 重命名为 UserId,仍然遵循约定,并在其他 POCO 中进行必要的更改以匹配更改。
采纳答案by tymtam
This is a guess :)
这是一个猜测:)
Is it because the ID is a string? What happens if you change it to int?
是因为ID是字符串吗?如果将其更改为 int 会发生什么?
I mean:
我的意思是:
public int Id { get; set; }
回答by walther
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 intinstead 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
1.) 将 ID 的类型int改为字符串
2.) 不推荐!!!- 自己处理自动增量。您首先需要从数据库中获取最新值,将其解析为整数,将其递增并再次将其作为字符串附加到实体。非常糟糕的主意
First option requires to change every table that has a reference to this table, BUT it's worth it.
第一个选项需要更改每个引用此表的表,但这是值得的。

