实体框架标识自动递增实体、标识、框架

2023-09-03 06:21:59 作者:任岁月静好

有与递增的问题。 我创建了一个新的对象,并试图将其设置为我的数据库我接收到的数据违反了一个错误。在表中的索引不增加(标识= 0)。 ID - 设置在SQL表和字段ID,在EDM设置为身份,所以,很明显,它必须自动增加的 StoredGeneratedPattern 属性主键

Have a problem with incrementing. I created a new object and tried set it into my DB I received an error of data violation. The index in table wasn't increased (Id=0). Id - set as primary key in SQL table and the StoredGeneratedPattern property of field "Id" in EDM set as "Identity" so, obviously, it must be incremented automatically.

public void AddPhone(UserPhone phone)
{
    context.AddToUserPhone(phone);
    context.SaveChanges();
}

我不明白这是为什么。

I can't understand why.

推荐答案

实体框架并不自动递增的ID。这就是数据库的工作。对数据库表中的ID列设置为IDENTITY列,这样它会自动递增。这时你会发现,当你的SaveChanges()手机的ID属性将被设置为数据库选择了它的价值。

Entity Framework does not automatically increment IDs. That's the database's job. Set the ID column on the database table as an IDENTITY column so that it will auto-increment. Then you should find that after you SaveChanges() the phone's ID property will have been set to the value the database chose for it.