为了账号安全,请及时绑定邮箱和手机立即绑定

使用实体框架插入后更新多列

使用实体框架插入后更新多列

C#
蛊毒传说 2023-09-16 16:08:46
我在表上创建了一个数据库触发器,该触发器在插入后更新表中的字段。使用 EF 进行插入时,我将获得 ID 和编号。在数据库上我创建了以下代码:create table Things (    ID int primary key identity not null,    Number nvarchar(20));create trigger UpdateThingsNumberTrigger on Thingsafter insertasbegin    declare @month nvarchar(2);    select @month = cast(month(getdate()) as nvarchar(2));    declare @code nvarchar(15);    select @code = cast(year(getdate()) as nvarchar(4)) +         '.' +         replicate('0', 2 - len(@month)) +         @month +         '.';    declare @max nvarchar(20);    select @max = t.ID    from Things t    where ID like @code + '%';    with CTE_UPD as     (        select             replicate('0',                 4 -                len(cast(coalesce(cast(right(@max, 4) as int), 0) + row_number() over (order by ins.ID) as nvarchar(4)))) +                 cast(coalesce(cast(right(@max, 4) as int), 0) + row_number() over (order by ins.ID) as nvarchar(4)) as NextNo,             ID        from Things ins    )       update Things    set Number = @code + NextNo     from Things t inner join CTE_UPD ins on ins.ID = t.ID;end我的代码的这一部分工作正常,忽略触发器内的逻辑缺陷......我将在这个问题中尝试解决的问题是当我从实体框架(首先是数据库)在表中插入一个东西时。这是我的代码和输出:using (Database db = new Database()){    Thing thing = new Thing(); // --> just an empty constructor.    db.Entry(thing).State = EntityState.Added;    await db.SaveChangesAsync();    Console.WriteLine($"ID = {thing.ID}");    Console.WriteLine($"Number = {thing.Number}");}// Output:// ID = 1// Number = 在后台 EF 调用时在服务器上执行此代码SaveChangesAsync():INSERT [dbo].[Things]([Number])VALUES (NULL)SELECT [ID]FROM [dbo].[Things]WHERE @@ROWCOUNT > 0 AND [ID] = scope_identity()现在可以 EF 更新 C# 对象中的 ID。但是,在关闭 using 块之前,如何在不使用下面的代码的情况下获取数字?Thing recentlyInsertedThing = await db.Things.FindAsync(thing.ID);
查看完整描述

1 回答

?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

我发现它无需编写第二个select语句即可获取 ID 和编号。这是我的代码:


using (Database db = new Database())

{

    Thing thing = new Thing();

    string sql = @"insert into Things() 

                    values ();

                    select ID, Number

                    from Things

                    where @@rowcount > 0 and ID = scope_identity();";


    KeyMapper recentlyRecevedKeys = await db

        .Database

        .SqlQuery<KeyMapper>(sql)

        .FirstAsync();


    thing.ID = recentlyRecevedKeys.ID;

    thing.Number = recentlyRecevedKeys.Number;  

}


// Nested class

private class KeyMapper

{

    public int ID { get; set; }

    public string Number { get; set; }

}


查看完整回答
反对 回复 2023-09-16
  • 1 回答
  • 0 关注
  • 54 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信