简体   繁体   English

如何使用Entity Framework生成和自动增加Id

[英]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: 我正试图通过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. 虽然如果我手动发送随机ID和请求,那么一切都很好。 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? 为什么实体框架不会生成并自动增加Id? My POCO class is as follows: 我的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(); 在调试模式下,我通过Fiddler发送请求,它在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. 将字符串Id更改为int,然后删除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重命名为UserId,仍遵循惯例,并在必要时在其他POCO中进行更改以匹配更改。

This is a guess :) 这是猜:)

Is it because the ID is a string? 是因为ID是一个字符串吗? What happens if you change it to int? 如果将其更改为int会发生什么?

I mean: 我的意思是:

 public int Id { get; set; }

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 1.)将ID的类型更改为int而不是string
2.) not recommended!!! 2.)不推荐!!! - 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. 第一个选项需要更改每个引用此表的表,但这是值得的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 首先在Entity Framework数据库中生成并自动递增ID - Generate and auto increment the Id in Entity Framework database first 复合键实体框架中的自动递增 ID - Auto Increment ID in Composite key Entity Framework 如何在C#中使用Entity Framework使用字符串值生成自动增量编号 - How generate auto increment no with string value using Entity Framework in C# 创建没有自动增量ID的实体框架表 - Creating Entity Framework Table That Does Not Have Auto Increment Id C#实体框架迁移,使ID自动递增 - C# Entity Framework migration, Make ID auto-increment 如何使用自动增量键在表中查找特定实体? (实体框架) - How to find specific entity in a table with auto increment key? (Entity framework) 实体框架核心-如何通过编程关闭自动增量? - Entity Framework Core - how to programmability turn off auto increment? 如何使用内存数据库中的实体框架核心自动增加列? - How to auto increment a column using an Entity Framework core in memory database? 如何使用具有自动增量列的实体框架插入数据行 - How to insert data row using Entity Framework with Auto Increment column 如何使用 EF Core Oracle 生成和自动递增 Id - How to generate and auto increment Id with EF Core Oracle
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM