gpt4 book ai didi

c# - 如何在插入前更新 LINQ 类

转载 作者:太空宇宙 更新时间:2023-11-03 19:10:05 25 4
gpt4 key购买 nike

我试图在插入期间使用 LINQ/SQL 访问自动生成的主键。我需要在类的名称属性中使用该值:

Incident inc = new Incident
{
StartDateTime = DateTime.Now
};

Model.db.Incidents.InsertOnSubmit(inc);
inc.Name = "Incident #" + inc.ID;

try
{
Model.db.SubmitChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
Model.db.SubmitChanges();
}

我可能以错误的方式解决了这个问题。任何援助将不胜感激。谢谢。

最佳答案

这可能是存储过程(仍可在 Linq 中使用)非常适合的时候。

因此,我将概述 2 种方法来处理此问题:一种需要更多工作但性能更好,第二种只需修改您的代码以使其按原样工作。

为什么您的代码不起作用:原因是,您无法在插入之前获得 ID - 它尚不存在。

所以,在 Linq 中,您需要

  1. Insert new record
  2. Update the Name to include the generated ID
  3. Save again

这将导致 2 次完整的数据库往返;


为了避免 2 次数据库往返,您可以在 SQL 中创建一个简单的存储过程,并将它拖到您的 Linq 类中,在那里它将作为一种方法可用。

在存储过程中,您将插入新记录,然后立即使用生成的 ID 更新名称:

伪代码:

Create Procedure dbo.Incident_InsertAndUpdateName
@ ... [ your entity vars ]
As
Begin
Insert Into [ table ]
Select @[your list of vars]

Declare @NewID int
Set @NewID = Select @@Identity

Update [ table ]
Set Name = "Incident #" + Convert(Varchar(10), @NewID)
Where ID = @NewID
End

然后,在 Linq 中,一旦您将存储过程放入 DBML 类中,您只需调用

// by dragging the Stored Proc from designer onto your Incident table, 
// LINQ will generate a mapping from the stored procedure to the Incidents entity
// such that you don't have to map the fields yourself
Model.db.Incident_InsertAndUpdateName(inc);

这是高效的方式;要修改您的代码,您可以这样做:

    Incident inc = new Incident
{
StartDateTime = DateTime.Now
};

Model.db.Incidents.InsertOnSubmit(inc);
try
{
Model.db.SubmitChanges();
inc.Name = "Incident #" + inc.ID;
Model.db.SubmitChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
}

关于c# - 如何在插入前更新 LINQ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21442287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com