Set a custom identity value on a auto increment field

和自甴很熟 提交于 2019-12-02 21:06:30

问题


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

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.

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

Thanks in advance!


回答1:


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

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.

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

Something like this

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
            }
    }

}



回答2:


I don't like to say flat-out that it's impossible, but this is pretty inside baseball for L2E. But it's a pretty simple INSERT trigger. You'll get the inserted row via INSERTED (Google will explain), and then you update that row with whatever crazy logic you want.

I think you can bang your head against L2E for hours trying to figure it out, or do it inside of twenty minutes with a trigger.



来源:https://stackoverflow.com/questions/5639563/set-a-custom-identity-value-on-a-auto-increment-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!