0

I have the following in my db with a junction/xref table enter image description here

I would like to map it to the following object

 public class Coin : CoinBase
{


    public IEnumerable<CoinAnnouncement> Announcements { get; set; }
    public IEnumerable<CoinCategory> Categories { get; set; }


}

I would like to include annoucements in one go as well if possible (not showing in the db image)

Here is my dapper call

 using (var conn = new SqlConnection(connectionString))
        {
            conn.Open();
            return await conn.QueryAsync<Coin, CoinCategory, Coin>(
                @"SELECT c.CoinId, c.Userid, c.IconPath, c.LastPriceBtc, c.LastUpdatedUtc, c.Name, c.Rank,
                         c.Symbol, c.LogoPath, c.Description, c.SubReddit, c.TwitterScreenName, c.Website, c.Discord,
                         c.FacebookPage, c.Telegram
                FROM Coins c
                INNER JOIN CoinCategoriesCategories coinCat ON coinCat.CoinId = c.CoinId
                INNER JOIN CoinCategories cat ON cat.CategoryId = coinCat.CategoryID", 
                (coin, coinCat) => {

                    coin.Categories = coinCat; //problem figuring out what this line would look like
                    return coin;
                });
        }

I essentially want to just ignore the xref/junction table and directly map the categories to the coin object

1

1 Answer 1

0

Solved it based on https://www.tritac.com/blog/dappernet-by-example

      var lookup = new Dictionary<int, Coin>();

        using (var conn = new SqlConnection(connectionString))
        {
            conn.Open();
            var result = await conn.QueryAsync<Coin, CoinCategoryCategory, CoinCategory, Coin>(
                @"SELECT c.*, coinCat.*, cat.*
                    FROM Coins c
                    INNER JOIN CoinCategoriesCategories coinCat ON coinCat.CoinId = c.CoinId
                    INNER JOIN CoinCategories cat ON cat.CategoryId = coinCat.CategoryID", 
                (c, cat, coinCat) =>
                {

                    Coin coin;
                    if (!lookup.TryGetValue(c.CoinId, out coin))
                    {
                        lookup.Add(c.CoinId, coin = c);
                    }
                    if (coin.Categories == null)
                        coin.Categories = new List<CoinCategory>();
                    coin.Categories.Add(new CoinCategory { CategoryId = coinCat.CategoryId, Description = coinCat.Description });
                    return coin;
                }, splitOn: "CategoryId, CoinId");

            return lookup.Values;
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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