如何强制插入并保留身份值?

时间:2019-07-03 10:35:46

标签: entity-framework entity-framework-6

我创建了一个ADO.NET实体数据模型,然后从数据库中选择EF设计器。在我的Cage表中,我有一列带有主键Identity CageNo。 我有这样的代码:

public static void Insert<T>(this DbContext context, T obj, bool InsertKeepIdentity = false) where T : class
    {
        if (InsertKeepIdentity)
        {
            context.SetIdentityInsert<T>(true);
        }
        context.Entry(obj).State = EntityState.Added;
        if (InsertKeepIdentity)
        {
            context.SaveChanges();
            context.SetIdentityInsert<T>(false);
        }
    }
public static string GetTableName<T>(this DbContext context) where T : class
    {
        ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;

        return objectContext.GetTableName<T>();
    }

    public static string GetTableName<T>(this ObjectContext context) where T : class
    {
        string sql = context.CreateObjectSet<T>().ToTraceString();
        Regex regex = new Regex("FROM (?<table>.*) AS");
        Match match = regex.Match(sql);

        string table = match.Groups["table"].Value;
        return table;
    }
public static int SetIdentityInsert<T>(this DbContext context, bool isOn) where T : class
    {
        return context.Database.ExecuteSqlCommand($"SET IDENTITY_INSERT {context.GetTableName<T>()} {(isOn ? "ON" : "OFF")}");
    }

我有这样的错误:

  

SqlException:当IDENTITY_INSERT设置为ON或复制用户插入到NOT FOR REPLICATION身份列中时,必须为表'Cage'中的身份列指定显式值。

像这样的查询

  

exec sp_executesql N'INSERT [dbo]。[笼子]([CageId],[IsActive],[折旧],[描述],[CreatedOn],[UpdatedOn],[SeedlingNo],[IsSystem])   值(@ 0,@ 1,@ 2,NULL,@ 3,@ 4,@ 5,@ 6)   选择[CageNo]   来自[dbo]。[笼子]   @@ ROWCOUNT> 0 AND [CageNo] = scope_identity()',N'@ 0 varchar(100),@ 1位,@ 2小数(19,4),@ 3 datetime2(7),@ 4 datetime2(7) ),@ 5 bigint,@ 6位',@ 0 ='K0001',@ 1 = 1,@ 2 = 2000.0000,@ 3 ='2019-06-29 10:51:26.6570000',@ 4 ='2019- 07-03 17:22:16.1011887',@ 5 = 4,@ 6 = 0

笼表:

CREATE TABLE [dbo].[Cage]
(
    [CageNo] BIGINT NOT NULL IDENTITY , 
    [CageId] VARCHAR(100) NOT NULL, 
    [IsActive] BIT NOT NULL, 
    [Depreciation] MONEY NOT NULL, 
    [Description] VARCHAR(MAX) NULL, 
    [CreatedOn] DATETIME NOT NULL, 
    [UpdatedOn] DATETIME NOT NULL, 
    [SeedlingNo] BIGINT NULL, 
    [IsSystem] BIT NOT NULL DEFAULT 0, 
    CONSTRAINT [PK_Cage] PRIMARY KEY ([CageNo]), 
    CONSTRAINT [AK_Cage_Column] UNIQUE ([CageId])
)

为什么没有插入或生成对CageNo的查询?

0 个答案:

没有答案