在自动递增字段上设置自定义标识值 [英] Set a custom identity value on a auto increment field

查看:82
本文介绍了在自动递增字段上设置自定义标识值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库(Sql server 2008)中有一个id列,其中设置了自动数字. 我正在使用EF和linq2entities

I have in my DB (Sql server 2008) a id column with auto numeric set on. I'm using EF and linq2entities

在某些特定情况下,我希望能够设置自定义ID号(显然,我完全确定不会重复此值),例如,我将使用它来填充"由删除导致的丢失ID号.我想将自动增量道具保留在数据库中,问题是当我执行linq语句时,数据库会分配下一个ID号,而不是我喜欢的ID号.

In some specific scenario I would like to be able to set a custom Id number (obviously I'm totally sure this value is not repeated), for example I would use it to "fill" missing Id numbers caused by deletions. I want to keep the auto increment prop in database, the problem is that when I do the linq sentence, the database assign the next Id number, not the one that I like.

也许有点奇怪,但是可以使用linq2entities吗?

Maybe it's a little weird but is it possible to do using linq2entities ?

提前谢谢!

推荐答案

我相信除非有某种方法可以在实体框架中关闭"SET Identity_Insert TableName ON",否则这是不可能的.

I believe Its not possible unless there is some way to turn off "SET Identity_Insert TableName ON" within Entity Framework.

基本上在SQL Server中,当您在字段上发送身份信息时,除非您运行以下语句,否则无法手动填充该信息

Basically in SQL Server when you sent Identity on a field it cannot be populated manually unless you run the following statement

SET Identity_Insert TableName ON

运行此语句后,您将能够手动填充身份字段".

After running this statement you will be able to populate Identity Fields manually.

我唯一想到的其他选择是从列中删除Identity属性,并使用部分类为Entity Framework中的字段创建自己的增量器

The only other options I can think of is to remove the Identity attribute from the column and create your own incrementer for the field in the Entity Framework using a partial Class

类似这样的东西

public partial class EntityClassName : global::System.Data.Objects.DataClasses.EntityObject, IEntity
{
    partial void InitializeFields();

    Int64 IEntity.IdentityColumn
    {
        get { return IdentityColumn; }
        set { //some code for an incrementer 
              //and the ability to set manually 
              //if value provide is not null
            }
    }

}

这篇关于在自动递增字段上设置自定义标识值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆