Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Create Dynamic Type in C# for Dapper

I have an application in which I'm saving unknown structured data. So, let's assume for a moment there is a table in the database named Foo and it looks like this:

CREATE TABLE [dbo].[Foo]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [DataId] INT NOT NULL, 
    [Bar] VARCHAR(50) NOT NULL, 
    CONSTRAINT [FK_Foo_Data] FOREIGN KEY ([DataId]) REFERENCES [Data]([Id])
)

And Foo is related to a table named Data which is going to store the provider who logged the data as well as the date and time it was logged, and let's say that table looks like this:

CREATE TABLE [dbo].[Data]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [ProviderId] INT NOT NULL, 
    [RecordDateTime] DATETIME NOT NULL, 
    CONSTRAINT [FK_Data_Provider] FOREIGN KEY ([ProviderId]) REFERENCES [Provider]([Id])
)

Okay, now let's assume that the provider (which I have no knowledge of the data it's providing) has a class named Foo that looks like this:

[Serializable]
public class Foo : ISerializable
{
    private string bar;

    public string Bar
    {
        get { return bar; }
        set { bar = value; }
    }

    public Foo()
    {
        Bar = "Hello World!";
    }

    public Foo(SerializationInfo info, StreamingContext context)
    {
        this.bar = info.GetString("Bar");
    } 

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Bar", bar);
    }
}

So, when the provider sends me an instance of Foo I'm going to interrogate it and determine which table in the database it should be inserted into, and let's assume that code block looks like this:

this.connection.Open();

try
{
    var parameters = new
        {
            ProviderId = registeredProvidersIdBySession[providerKey.ToString()],
            RecordDateTime = DateTime.Now,
        };

    var id = connection.Query<int>("INSERT INTO Data (ProviderId, RecordDateTime) VALUES (@ProviderId, @RecordDateTime); SELECT CAST(SCOPE_IDENTITY() as INT)", parameters).Single();

    var t = data.GetType();
    var fields = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);

    var tableName = string.Format("[{0}]", t.Name);
    var fieldList = string.Join(", ", fields.Select(p => string.Format("[{0}]", p.Name)).ToArray());

    var valueList = fields.Select(p => string.Format("@{0}", p.Name)).ToList();
    valueList.Insert(0, "@DataId");

    var values = new Dictionary<string, object>();
    values.Add("@DataId", id);
    foreach (var propertyInfo in fields)
    {
        values.Add(string.Format("@{0}", propertyInfo.Name), propertyInfo.GetValue(data, null));
    }

    return connection.Execute(string.Format(
        "INSERT INTO {0} ({1}) VALUES ({2})",
            tableName,
            fieldList,
            string.Join(", ", valueList.ToArray())), values);
}
finally
{
    this.connection.Close();
}

Now as you can see, I'm getting the tableName from the Type of the object passed to me. In our example that's Foo. Further, I'm gathering the list of fields to insert with reflection. However, the hitch in the get along is that Dapper requires an object be sent to it for the parameter values. Now, if I didn't need to provide the DataId property on the type I could just pass in the object that was given to me, but I need that DataId property so I can relate the log correctly.

What am I Asking?

  1. Am I going to have to create a dynamic type or can Dapper do something else to help?
  2. If I'm going to have to create a dynamic type, is there a more straight forward way than using the TypeBuilder? I've done it before, and can do it again, but man it's a pain.
  3. If I'm going to have to use the TypeBuilder I'd be interested in your example because you may know of a more efficient way than I do. So please include an example if you have some thoughts.

DISCLAIMER

In the code example above you see I tried passing in a Dictionary<string, object> instead but Dapper doesn't accept that. I pretty much knew it wouldn't because I'd already looked at the source code, but I was just hoping I missed something.

Thanks all!

Upvotes: 1

Views: 2875

Answers (2)

Felice Pollano
Felice Pollano

Reputation: 33242

There is a BuiltIn type in Dapper to pass parameter which properties are known runtime only: check the class DynamicParameters. It is used like:

var p = new DynamicParameters();
p.Add("@a", 11);
p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output);
p.Add("@c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

and then passed as a parameter object to the Execute method. It is typically used with SP ( so you can use it also for reading the output values) but there are no reasons preventing it to work with regular SELECT/INSERT/UPDATE queries.

Upvotes: 3

iamkrillin
iamkrillin

Reputation: 6876

I know you asked about dapper but...

Sauce DB actually handles this type of scenario pretty well. There are a few ways you can do it. Below is some example code that illustrates it. Note: you can override how the table name is found and there are method that allow you to retrieve the resolved table name if you wish.

Disclamer: I wrote SauceDB

public class Foo
{
    public int ID { get; set; }
    publi string Name { get; set; }
}

public class Bar
{
    public int ID { get; set; }
    publi string Name { get; set; }
}

public class  MainClass
{
    IDataStore _dstore;
    public void Main()
    {
        _dstore = new SqlServerDataStore("my_connection_string")//create data store

        InsertObject(new Foo());
        InsertObject(new Bar());
    }

    public void InsertObject(object o)
    {
        //this will assume the table it belongs to is the type name + an s
            //you can override the table name behavior as well
        _dstore.InsertObject(o);
    }
}

http://sauce.codeplex.com/

Upvotes: 1

Related Questions