亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用實體框架插入后更新多列

使用實體框架插入后更新多列

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 關注
  • 124 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號