I'm trying to determine how I should handle a one to many relationship in my DB, when using the data to build a model in C#. Ideally, I'd like to make a single call to the DB. However, it seems that two (or more) calls might be required.
For simplicity, assume my tables look like this...
CREATE TABLE [dbo].[Users]
(
[userId] INT PRIMARY KEY IDENTITY(0,1),
[userName] NVARCHAR(500) NOT NULL
)
CREATE TABLE [dbo].[Tasks]
(
[taskId] INT PRIMARY KEY IDENTITY(0,1),
[description] NVARCHAR(1000) NOT NULL,
[userId] INT FOREIGN KEY REFERENCES [dbo].[Users](userId)
)
So each user can have many tasks. I have a stored procedure that will return the details of a user, that looks like this...
CREATE PROCEDURE [dbo].[sp_GetUserDetail]
@userId INT
AS
BEGIN
SELECT
[dbo].[Users].[userName] AS 'User',
[dbo].[Tasks].[description] AS 'Task Description'
FROM
[dbo].[Users]
INNER JOIN
[dbo].[Tasks]
ON
[dbo].[Tasks].[userId] = [dbo].[Users].[userId]
WHERE
[dbo].[Users].[userId] = @userId
END
This procedure returns as many rows, as tasks that are assigned to a user. The model I'm trying to fill, would look something like this.
public interface User
{
string Name { get; set; }
List<string> Tasks { get; set; }
}
I see my options as follows:
- Use this code, and loop through the rows that are returned from the DB to build the Tasks list.
- Call one stored procedure to return the data from the Users table, then another to get the data from the Tasks table.
- Some (unknown to me magic) way to have a single stored procedure return all the data in a single row.
- Some other option I don't even know about.
How is this problem typically handled by experienced Developers?