实体框架中的新对象 - 主键问题

时间:2022-12-23 02:08:05

In my database I have a Vehicle table with a primary key. I am creating a new Vehicle object using

在我的数据库中,我有一个带有主键的Vehicle表。我正在使用创建一个新的Vehicle对象

new Vehicle();

and updating the properties of vehicle appropriately.

并适当更新车辆的属性。

When I try to do a

当我尝试做一个

genesisContext.Vehicles.AddObject(vehicle);

The first time the table is successfully updated and the primary key is 0. On all subsequent occasions I get an error saying that the key is not unique

第一次成功更新表并且主键为0.在随后的所有情况下,我都会收到错误消息,指出密钥不是唯一的

Violation of PRIMARY KEY constraint 'VEHICLES_PK'. Cannot insert duplicate key in object 'dbo.Vehicles'.\r\nThe statement has been terminated.

违反PRIMARY KEY约束'VEHICLES_PK'。无法在对象'dbo.Vehicles'中插入重复键。\ r \ n语句已终止。

(presumably because the primary key set by the EF is still 0)

(可能是因为EF设置的主键仍为0)

I was under the understanding that the EF intelligently works out primary keys so why is this happening??

我的理解是,EF智能地计算出主键,为什么会发生这种情况?

2 个解决方案

#1


You have two choices:

你有两个选择:

  • either you let the database handle the primary key, by specifying the VehicleID as INT IDENTITY(1,1) - in that case, SQL Server will automagically assign unique and individual numbers, and EF will be fine with that
  • 要么让数据库处理主键,要么将VehicleID指定为INT IDENTITY(1,1) - 在这种情况下,SQL Server将自动分配唯一和单独的数字,而EF将很好用

  • or you handle it yourself, e.g. you have to find a way in your app to come up with unique vehicle ID numbers.
  • 或者你自己处理,例如你必须在你的应用程序中找到一种方法来提出独特的车辆ID号码。

EF out of the box has nothing in it to magically dispense unique numbers for primary keys - if you thought that, it was a misconception.

开箱即用的EF没有任何内容可以神奇地为主键分配唯一的数字 - 如果你认为这是一个误解。

Marc

#2


You can assign the new id on SavingChanges events of ObjectContext

您可以在ObjectContext的SavingChanges事件上分配新ID

objectContext.SavingChanges += new EventHandler(objectContext_SavingChanges);

#1


You have two choices:

你有两个选择:

  • either you let the database handle the primary key, by specifying the VehicleID as INT IDENTITY(1,1) - in that case, SQL Server will automagically assign unique and individual numbers, and EF will be fine with that
  • 要么让数据库处理主键,要么将VehicleID指定为INT IDENTITY(1,1) - 在这种情况下,SQL Server将自动分配唯一和单独的数字,而EF将很好用

  • or you handle it yourself, e.g. you have to find a way in your app to come up with unique vehicle ID numbers.
  • 或者你自己处理,例如你必须在你的应用程序中找到一种方法来提出独特的车辆ID号码。

EF out of the box has nothing in it to magically dispense unique numbers for primary keys - if you thought that, it was a misconception.

开箱即用的EF没有任何内容可以神奇地为主键分配唯一的数字 - 如果你认为这是一个误解。

Marc

#2


You can assign the new id on SavingChanges events of ObjectContext

您可以在ObjectContext的SavingChanges事件上分配新ID

objectContext.SavingChanges += new EventHandler(objectContext_SavingChanges);