开发者

Does LINQ have an equivilant of @@IDENTITY or SCOPE_IDENTITY()?

开发者 https://www.devze.com 2023-01-12 13:19 出处:网络
Say that a page loads and the first thing I want to do is find the identity of the 开发者_如何学编程last record inserted into a table.

Say that a page loads and the first thing I want to do is find the identity of the 开发者_如何学编程last record inserted into a table.

I'm not going to be inserting any records or anything, i just want to come in blind and find the last id inserted, can it be done using LINQ?


A loaded collection doesn't know anything about storage (which handles auto increment values). If you want to know the highest id in a loaded collection you can use an aggregate linq query and select max id.

Or you can use Linq-To-Sql to run a stored procedure and retrieve SCOPE_IDENTITY.


You could always execute a snippet of T-SQL from Linq to get the values:

SELECT 
    name, 
    OBJECT_NAME(OBJECT_ID) 'Table name',
    ISNULL(last_value, -1) 'Last Value'
FROM 
    sys.identity_columns 

and then grab the necessary values from that output.


Have you tried BLToolkit. It supports LINQ as well as many other useful operations that are absent in LINQ2SQL: i.e DML with a human face :)

Regarding your question: BLToolkit contains InsertWithIdentity method

var value = db.Employee.InsertWithIdentity(() => new Northwind.Employee
{
    FirstName = "John",
    LastName  = "Shepard",
    Title     = "Spectre",
    HireDate  = Sql.CurrentTimestamp
});

or

var value =
    db
    .Into(db.Employee)
        .Value(e => e.FirstName, "John")
        .Value(e => e.LastName,  "Shepard")
        .Value(e => e.Title,     () => "Spectre")
        .Value(e => e.HireDate,  () => Sql.CurrentTimestamp)
    .InsertWithIdentity();


Hi men's i have a solution on linq whit vb.net!

        Dim Reg as new Consult
        Reg.Nombre = TxName.Text
        Reg.Edad = TxYears.Text
        Reg.Pulso = TxPulse.Text
        Reg.Tension = TxTens.Text
        Reg.Peso = TxKg.Text
        Db.Consulta.InsertOnSubmit(Reg)
        Db.SubmitChanges()
        MsgBox("You have created a New Consult #" & Reg.ConsultaId)

        DialogResult = Windows.Forms.DialogResult.OK
        Me.Close()

THIS WORK FOR ME!!!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号