一尘不染

如何使用实体框架生成和自动增加ID

json

修改了 整个帖子。

我正在尝试通过Fiddler发布以下JSON POST请求:

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

但是我收到此错误:

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

尽管如果我随请求手动发送一个随机ID,那么一切都很好。像这样:

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

为什么实体框架不生成ID并自动递增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; }
}

这是控制器方法。在调试模式下,我通过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);
        }
    }

怎么了?

将字符串ID改为int并删除数据注释。仍遵循约定将ID重命名为UserId,并在必要时在其他POCO中进行了更改以与更改匹配。


阅读 321

收藏
2020-07-27

共1个答案

一尘不染

这是一个猜测:)

是因为ID是字符串吗?如果将其更改为int会怎样?

我的意思是:

 public int Id { get; set; }
2020-07-27