本文介绍了实体框架中的新对象 - 主键的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  new Vehicle()创建一个新的车辆 

并适当更新车辆的属性。



当我尝试做一个

  genesisContext.Vehicles.AddObject (车辆); 

表首次成功更新,主键为0.在以后的任何时候,我得到一个错误,说密钥不是唯一的

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

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

解决方案

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
  • or you handle it yourself, e.g. you have to find a way in your app to come up with unique vehicle ID numbers.

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.

Marc

这篇关于实体框架中的新对象 - 主键的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 00:34