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?
- Am I going to have to create a dynamic type or can
Dapperdo something else to help? - 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. - If I’m going to have to use the
TypeBuilderI’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!
There is a BuiltIn type in Dapper to pass parameter which properties are known runtime only:
check the class
DynamicParameters. It is used like:and then passed as a parameter object to the
Executemethod. 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.