Can I return a collection of multiple Derived Types from Dapper query

僤鯓⒐⒋嵵緔 提交于 2019-12-04 00:23:47

In the current build that is probably the only option (especially since the base-type is abstract). However, it wouldn't be unreasonable to think of ways of suggesting a discriminated inheritance system. It isn't something we've done so far simply because it hasn't come up - but it doesn't sound impossible. The biggest problem I can see (other than IL-wrangling, obviously) is simply how we express the relationship.

I've came up with this solution:

using (IDbConnection db = new MySqlConnection(ConfigurationManager.ConnectionStrings["yourConnection"].ConnectionString))
        {
            return db.Query<dynamic, DeviceA, DeviceB, Device>(@"
                Select
                    Discriminator,
                    ...
                From Device", (d, da, db) =>
                {
                    if (p.Discriminator == "DeviceA")
                    {
                        return new DeviceA();
                    }
                    else if (p.Discriminator == "DeviceB")
                    {
                         return new DeviceB();
                    }
                    return d;
                });       

Sounds tricky, but it does work!

Hope it can help you. }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!