2

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?

1 Answer 1

1

Yes...it is possible. There are a couple of ways of addressing the "one-to-many" scenario with dapper:

METHOD 1 - Return two queries, combine in DAL

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();
}

METHOD 2 - Return one query, split in DAL

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

Enhancements

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; }
}
11
  • Great I'll give this a go. From first glance I like option 2...keeping as much logic as possible in the code and keeping the stored proc 'cleaner' Mar 31, 2017 at 20:01
  • 1
    The downside to option 2 is that the query size will be fatter...if a car has 50 options, that column data is repeated 50 times (once for each option). Not a huge concern, but there anyhow. Mar 31, 2017 at 20:10
  • Good point. It could have up to 70 options...unlikely to have more than 10 but the possibility is that it could have up to 70. Is there any drawback you could see with option 1 apart from have a bit too.much logic in the SP. I guess having logic in SP has the advantage of being straightforward to deploy if a fix was required Mar 31, 2017 at 21:40
  • 1
    I think of what you are doing as query logic as opposed to business logic. Query logic(filtering, retrieving) is perfectly acceptable in a sproc. By the way, does it have to be a sproc? It is soooo much easier to maintain if you pass in the sql directly (use resource files to help manage your sql files too). We converted hundreds of procs and are perfectly happy. Apr 1, 2017 at 11:36
  • 1
    Ok...another tip for the first method is to simply make one query into a temp table that stores your carID and accounts for your filtering (WHERE clause) in one place. Then, make two extremely clean selects joining the carIDs you just put in a temp. Basically: 1.) insert into @t select CarID where @cust=xxx...2.) select * from Cars c inner join @t t ON t.CarID = c.CarID 3.) select * from CarOptions co inner join @t t ON t.CarID = co.CarID. Apr 1, 2017 at 20:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.