Search code examples
c#sqlcsla

Insert using DataContext and getting ID CSLA C#


How can I retrieve the ID during an insert in C# using CSLA? The stored procedure does an insert into the database table and then has a SELECT @Id (which is set with the SCOPE_IDENTITY()) after the insert.

This is the code to insert in C#:

using (var mgr = ContextManager<PersonDataContext>.GetManager("TestDB"))
{
    var results = mgr.DataContext.up_StoredProcToInsert(
        "David",
        30,
    );
}

Solution

  • try below example based on CRUD Operations using Stored Procedure in Entity Framework:

    SP:

    CREATE PROCEDURE SP_Ins_Test 
        @name nchar(10)
    AS
    BEGIN
    
        SET NOCOUNT ON;
        INSERT INTO dbo.test(name)
        SELECT @name
    
        SELECT SCOPE_IDENTITY() AS ResultId
    END
    GO
    

    C# code:

    DemoDB_JRDevEntities db = new DemoDB_JRDevEntities();
    SP_Ins_Test_Result r=db.SP_Ins_Test("Raj").First();
    string id= r.ResultId.ToString();