Insert using DataContext and getting ID CSLA C#

354 views Asked by At

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,
    );
}
2

There are 2 answers

0
Divyesh patel On BEST ANSWER

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();
0
Rockford Lhotka On

Although the sample doesn't use a stored procedure, relying on EF to do the work itself, you can look at the EF data access layer in the ProjectTracker sample to see how an insert operation is implemented:

https://github.com/MarimerLLC/csla/blob/master/Samples/ProjectTracker/ProjectTracker.DalEf/ProjectDal.cs#L82

    public void Insert(ProjectDto item)
    {
      using (var ctx = ObjectContextManager<PTrackerEntities>.GetManager("PTrackerEntities"))
      {
        var newItem = new Project
        {
          Name = item.Name,
          Description = item.Description,
          Started = item.Started,
          Ended = item.Ended
        };
        ctx.ObjectContext.AddToProjects(newItem);
        ctx.ObjectContext.SaveChanges();
        item.Id = newItem.Id;
        item.LastChanged = newItem.LastChanged;
      }
    }