Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8617991
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T06:00:22+00:00 2026-06-12T06:00:22+00:00

I have an application in which I’m saving unknown structured data. So, let’s assume

  • 0

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!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T06:00:23+00:00Added an answer on June 12, 2026 at 6:00 am

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an application which is receiving data for thousands (say 50,000) subjects. Each
I have a application which handles picture chosen from gallery. But there is a
I have an application which reads in gridded coordinate data with values (i.e. lat,
I have an application which receives data from a news website (through rss) and
I have application implemented which having the SQL Server 2008 database at back end.
I have an application which grabs some data with the following sql: SELECT Sum(fieldname)
I have application which exports data in csv file which is stored in Document's
I have an application which extracts data from an XML file using XPath. If
I have an application which keeps its data in a directory tree. Now, I
I have an application which posts progress/status messages as it runs (it's a database

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.