gilmishal
gilmishal

Reputation: 1982

Dapper factory object construction

I have something like the following query

_connection.Query<SomeType>(SELECT Id, Type, Time FROM table)

the thing is SomeType is a generic type

public class SomeType<T>
{
    public int Id { get; set; }
    public SomeTypeType Type { get; set; }
    public DateTime Time { get; set; }
    public T Object { get; set; }
}

right now I can define some sort of SomeType<object> or whatever, and in order to use the correct generic SomeType<T> I need to reconstruct the object.

what I want to be able to do is to have a line such as this that will actually work

var x =  _connection.Query<SomeType<object>>("...") as SomeType<OtherType>

(Obviously this is not a good example, but in my case it makes much more sense)

Any way, this obviously returns null, and just won't really work.

I thought maybe by defining some other way to construct the type, by maybe hooking to the way dapper initializes the type and defining a Factory or something.

Any suggestions to how I can actually do that?

Upvotes: 1

Views: 607

Answers (1)

user310988
user310988

Reputation:

I'm not aware of any configurable factories for the types used in Dapper.

I had a quick look at the code on github and there was nothing obvious, but I didn't do an exhaustive search.

There are TypeHandlers, but they seem to be more for mapping value types, the properties on the model object, rather than modifying the modelobject itself.

So I think you'll have to handle this in a more manual way:

public class SomeType
{
    public int Id { get; set; }
    public SomeTypeType Type { get; set; }
    public DateTime Time { get; set; }
    public T Object { get; set; }
}

public class SomeType<T> : SomeType
{
    public T Object { get; set; }

    public SomeType() { }
    public SomeType(SomeType someType, T obj)
    {
        this.Id = someType.Id;
        ...
        this.Object = obj;
    }
}

var someType = _connection.Query<SomeType>("SELECT Id, Type, Time FROM table");
var obj = new Foo();
var specialisedSomeType = new SomeType<Foo>(someType, obj);

The manual mapping from 'SomeType' to 'SomeType' in the constructor can get tedious, so you could use something like AutoMapper to handle that bit.

Upvotes: 1

Related Questions