Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting object that should be mapped into different DB table depending on scenario

I have an object with properties names that exactly name the field names inside the DB table but I'm not sure how to insert it. The only thing different is the DB table name. So it's an object with a name of different model/mapped table but I want it to be inserted into a table with a different name than the model. I tried this:

var val = info.FooBarObj;
conn.Execute("insert DBInformation(val) values(@val)", new { val = val }); 

Where e.g.

Object is FooBarObj and properties are int Id, string Foo, string Bar

and the DBInformation has the field names: Id, Foo, and Bar but the table isn't called FooBarObj, it's called DBInformation.

How can I insert something like this? I'm using Dapper

EDIT:

Can I have two table attributes for FooBar model?

E.g. [Table("DBInformation")] and [Table("FooBar")].

I have a weird edge case where I want to insert into FooBar if this scenario occurs, if another scenario occurs, insert into DBInformation. That's the problem I'm currently facing and thus that's why I can't just add the attribute and be done with for this problem.

like image 881
Euridice01 Avatar asked Oct 27 '17 15:10

Euridice01


1 Answers

Check out the Dapper.Contrib project. It allows you to decorate your model classes with some useful attributes.

Use the Table attribute on your FooBar class to identify that this should be mapped to the DBInformation table. For example:

[Table("DBInformation")]
public class FooBar
{
    #region Properties

    [ExplicitKey] // Use this attribute if your ID field is not automatically generated, (identity)
    public int Id { get; set; }
    public string Foo { get; set; }
    public string Bar { get; set; }
    ...
}

And another advantage to using Dapper.Contrib is that it will allow you to perform CRUD operations very easily. For example, for insert:

using (var conn = new SqlConnection(connectionString))
{
     conn.Insert(myFooBar);
}

and for update:

using (var conn = new SqlConnection(connectionString))
{
     conn.Update<FooBar>(myFooBar);
}

etc.

EDIT

To address what your "real" problem is, (your latest edit from the original), where you need to potentially insert into two tables depending on a particular scenario, then I would go back to just adjusting your SQL that you provide dapper:

string theTable = someCondition : "DBInformation" : "FooBar"; 
using (var conn = new SqlConnection(connectionString))
{
    conn.Insert(myFooBar);
    string insertSql = $"INSERT INTO {theTable} ([Id], [Foo], [Bar]) VALUES @FooBarObj.Id, @...)";            
    var result = conn .Execute(insertSql , myFooBar);
}
like image 143
flyte Avatar answered Oct 10 '22 04:10

flyte