I am trying to return data using Dapper via stored proc
My DTO Class is similar to below (removed some properties for brevity)
public class CarDTO
{
public int CarID { get; set; }
public string Manufacturer { get; set; }
public List<CarOptionDTO> CarOptions { get; set; }
}
So basically in the DB I have a CarOption table that has a CarID column - i.e a Car can have many options.
My DAL Layer call at the minute is as below:
private string getCarDataSp = "[dbo].[GetCarData]";
public IEnumerable<CarDTO> GetCarData(int customerId, int year)
{
return Get(db => db.Query<CarDTO>(getCarDataSp , new { CustomerID = customerId, Year = year },
commandType: CommandType.StoredProcedure));
}
Implementation of my Get function is in my BaseRepository class as:
public T Get<T>(Func<IDbConnection, T> query)
{
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDB"].ConnectionString))
{
return query.Invoke(db);
}
}
Is it possible using Dapper I can return from my stored proc the CarOptions as well?
My stored proc at the minute is as below:
ALTER PROCEDURE [dbo].[GetCarData]
@CustomerID int,
@Year int
AS
BEGIN
SET NOCOUNT ON;
SELECT * from [dbo].Car c
JOIN [dbo].Customer cust ON c.CarID = cust.CarID
WHERE cust.CustID = @CustomerID AND cust.Year = @Year
END
the query above may return many rows and the CarID and Manufacturer and the other properties I removed for Brevity. Dapper will map those back to the DTO as expected.
However, it is how to return the list of CarOptions in the stored proc - is it possible with another query or should it be separated out somehow? If I have CarID 1 and CarID 2 returned, for example, there may be 6 rows in the CarOption table with CarID 1 and 4 rows in the CarOption table with CarID 2 and ideally, I would like them all to be returned to the CarOptions collection via Dapper if possible?
Yes...it is possible. There are a couple of ways of addressing the "one-to-many" scenario with dapper:
ALTER PROCEDURE [dbo].[GetCarData]
@CustomerID int,
@Year int
AS
BEGIN
SET NOCOUNT ON;
--return cars
SELECT c.*
from [dbo].Car c
INNER JOIN [dbo].Customer cust ON c.CarID = cust.CarID
WHERE cust.CustID = @CustomerID AND cust.Year = @Year
--return options
SELECT opt.*
from [dbo].Car c
INNER JOIN [dbo].Customer cust ON c.CarID = cust.CarID
INNER JOIN dbo.CarOptions opt ON op.CarID = c.CarID
WHERE cust.CustID = @CustomerID AND cust.Year = @Year
END
DAL
var multi = db.QueryMultiple(getCarDataSp , new { CustomerID = customerId, Year = year },
commandType: CommandType.StoredProcedure));
var cars = multi.Read<CarDTO>();
var options = multi.Read<CarOptionDTO>();
//wire the options to the cars
foreach(var car in cars){
var carOptions = options.Where(w=>w.Car.CarID == car.CarID); //I would override Equals in general so you can write w.Car.Equals(car)...do this on a common DataModel class
car.Options = carOptions.ToList();
}
Proc
ALTER PROCEDURE [dbo].[GetCarData]
@CustomerID int,
@Year int
AS
BEGIN
SET NOCOUNT ON;
SELECT c.*, opt.*
from [dbo].Car c
INNER JOIN [dbo].Customer cust ON c.CarID = cust.CarID
LEFT OUTER JOIN dbo.CarOptions opt ON op.CarID = c.CarID
WHERE cust.CustID = @CustomerID AND cust.Year = @Year
END
DAL
var tuples = db.Query<CarDTO, CarOptionDTO,Tuple<CarDTO,CarOptionDTO>>(getCarDataSp , new { CustomerID = customerId, Year = year },
(car,opt)=> Tuple.Create(car,opt), commandType: CommandType.StoredProcedure);
//group tuples by car
var cars = tuple.GroupBy(gb=>gb.Item1.CarID) //again, overriding equals makes it so you can just to GroupBy(gb=>gb.Item1)
.Select(s=>{
var car = s.First().Item1;
var carOptions = s.Select(t=>t.Item2).ToList()
return car;
});
Using a temp table in the query
This puts all filtering by parameters into a single query. Subsequent queries are drop-dead simple selects by ID.
ALTER PROCEDURE [dbo].[GetCarData]
@CustomerID int,
@Year int
AS
BEGIN
SET NOCOUNT ON;
declare @t table(CarID int);
--filter cars (only deal with parameters here)
INSERT INTO @t(CarID)
SELECT c.CarID
FROM dbo.Car c
INNER JOIN [dbo].Customer cust ON c.CarID = cust.CarID
WHERE cust.CustID = @CustomerID AND cust.Year = @Year
--return cars
SELECT c.*
FROM [dbo].Car c
INNER JOIN @t t ON t.CarID = c.CarID
--return options
SELECT opt.*
FROM dbo.CarOptions opt
INNER JOIN @t t ON t.CarID = opt.CarID
END
Applying a BaseDTO to help with equality
Once you have the BaseDTO, and wire up your ID you can simply say things such as:cars.Where(w=>w.Equals(car)), dictionary[car] (if it's in there), if(car.Equals(otherCar)), or results.GroupBy(gb=>gb.Car)...
public class BaseDTO
{
internal int ID { get; set; }
/// <summary>
/// If the obj is the same type with the same id we'll consider it equal.
/// </summary>
public override bool Equals(object obj)
{
if(obj == null || this.GetType() != obj.GetType())
{
return false;
}
return this.GetType().GetHashCode() == obj.GetType().GetHashCode() &&
this.ID == (BaseDTO)obj.ID;
}
/// <summary>
/// If you override equals, you should override gethashcode.
/// http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode#263416
/// </summary>
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = hash * 23 + this.GetType().GetHashCode();
hash = hash * 23 + this.ID;
return hash;
}
}
}
public class CarDTO : BaseDTO
{
public int CarID
{
get { return this.ID; }
set { this.ID = value; }
}
public string Manufacturer { get; set; }
public List<CarOptionDTO> CarOptions { get; set; }
}