【问题标题】:Entity Framework 5 : Get Auto_Increment value before insert实体框架 5:插入前获取 Auto_Increment 值
【发布时间】:2013-11-18 19:25:51
【问题描述】:

我目前有一个表定义如下:

CREATE TABLE ( 
    ID int identity(1,1) primary key not null,
    field_one nvarchar(max) not null
)

我正在使用 Entity framework 5 将记录插入到此表中。这方面有效,我正在正确插入记录。

field_one 是基于当前 id 的值。例如,如果我有最大 ID 为 5 的记录,则下一条记录将插入为 (6,ABC6),然后是 (7, ABC7),依此类推。

我遇到的是桌子是空的。标识为 7,因此下一条记录应为 (8,ABC8)。我需要在插入之前获取 auto_increment 的 id,以便在表为空时应用我需要的计算。

我怎么能做到这一点,因为我知道 id 是在插入之后生成的,并且我的实体中的属性在之后更新。

【问题讨论】:

  • 不能,因为还没有创建。但是你可以取select top(id) from table + 1,但是如果你的设计以这个结尾,那你就做错了。
  • top id 不是一个好方法,因为您可能已经删除了一些记录,在这种情况下,top id 将不等于下一个生成的 id。您必须保存更改,然后将返回生成的 id。

标签: c# sql-server asp.net-mvc entity-framework


【解决方案1】:

在执行SaveChanges 之前,您无法获得正确的身份。这是因为它是由实体框架在插入时设置的。

但是,有一个解决您的问题的方法。

考虑一下:

// wrap in a transaction so that the entire operation 
// either succeeds or fails as a whole
using(var scope = new TransactionScope())
using(var context = new DbContext()) {
    var item = new Item();
    context.Items.Add(item);
    context.SaveChanges();
    // item.ID now contains the identifier
    item.field_one = string.Format("abc{0}", item.ID);
    // perform another save.
    context.SaveChanges();
    // commit transaction
    scope.Complete();
}

是的,有两次对数据库的调用,但没有其他方法,除非您准备好比 Entity Framework 更深入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 2016-05-09
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    相关资源
    最近更新 更多