Given business objects similar to:
public class MyBase
{
public int Id { get; set; }
}
public class Parent : MyBase
{
public List<Child> Children { get; set; }
// Additional objects with 1:1 relationship
}
public class Child : MyBase
{
public Parent Parent { get; set; }
public List<Grandchild> Grandchildren { get; set; }
// Some other properties
}
public class GrandChild : MyBase
{
public Child { get; set; }
// Some other properties including a timestamp
}
I'm trying to replace bulk insert functionality originally written with Entity Framework with ADO.Net and stored procedures due to the poor performance of EF in this scenario.
Not being a DB expert, I first oriented myself with
http://www.sommarskog.se/arrays-in-sql-2008.html
Using that guidance I was able to create a well-performing (relative to EF) stored procedure that inserts a Child
along with its List<GrandChild>
.
CREATE TYPE tvpInt32List AS TABLE (n int NOT NULL)
CREATE PROCEDURE uspInsertChild @parentId INT, @fk1Id INT, @fk2Id INT,
@listValues tvpInt32List READONLY
AS
DECLARE @id INT
BEGIN TRANSACTION
BEGIN TRY
INSERT INTO dbo.Children VALUES(@fk2Id, @fk1Id, NULL, 0, 1, NULL, NULL, NULL, NULL, NULL, @fk1Id, @parentId)
SET @Id = SCOPE_IDENTITY()
INSERT INTO dbo.Grandchildren SELECT n, '', GETDATE(), @id FROM @listValues
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH
However, I would like to take this a step further and create a stored procedure that accepts data for a Parent
object and then creates the associated List<Child>
, and the List<GrandChild>
for each Child
.
I'm conceptually at a loss as to how to approach that in a stored procedure.
What strategy can I use to pass in that type of data structure and process it in the stored procedure?