我可以返回多个派生类型的集合,从小巧玲珑的查询 [英] Can I return a collection of multiple Derived Types from Dapper query

查看:183
本文介绍了我可以返回多个派生类型的集合,从小巧玲珑的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的类结构:

I have a class structure similar to this:

public abstract class Device
{
    public int DeviceId { get; set; }
    //Additional Properties
}

public class DeviceA : Device
{
    //Specific Behaviour
}

public class DeviceB : Device
{
    //Specific Behaviour
}

我需要检索设备的列表,或者被实例化为相应的派生类型(基于在DB中的装置记录一个类型值)的单个设备。也就是说,设备对象的集合应该包含了许多不同类型,所有这一切都是从设备。

I need to retrieve a list of Devices, or a single Device which is instantiated as the appropriate derived type (based upon a Type value in the Device Record in the DB). That is, the collection of Device objects should contain a number of objects with different Types, all of which are derived from Device.

我已经实现了这个以下方式,但有些事情感觉不对了。

I have implemented this the following way, but something just doesn't feel right about it.

public static IEnumerable<Device> AllDevices()
{
    using (var connection = CreateConnection())
    {
        connection.Open();
        return connection.Query<dynamic>("SELECT * FROM Device").Select<dynamic, Device>(d =>
            {
                Device device = null;
                if (d.DeviceTypeID == 1)
                    device = new DeviceA();
                else if (d.DeviceTypeID == 2)
                    device = new DeviceB();
                else throw new Exception("Unknown Device");
                device.DeviceId = d.DeviceID;
                return device;
            });
    }
}

这是实现这一目标采用精致小巧的正确方法,还是有更好的方法?

Is this the correct way to achieve this using Dapper, or is there a better approach?

推荐答案

在目前的版本,也可能是唯一的选择(尤其是基本型是抽象)。但是,它不会是不合理的,认为这表明一个歧视的继承系统的方法。这是不是我们所做到目前为止,仅仅是因为它没有拿出 - 但它不健全是不可能的。我能看到的最大问题(比IL-扯皮,显然等)仅仅是我们如何表达的关系。

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.

这篇关于我可以返回多个派生类型的集合,从小巧玲珑的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆