5

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.

Euridice01
  • 2,510
  • 11
  • 44
  • 76
  • Are the two entities logically different, that is do they represent things – sQuir3l Nov 09 '17 at 13:28
  • @sQuir3l, yes and no. Basically, the other entity is a duplicate of the first entity and second entity is where the dups of the first entity are stored. – Euridice01 Nov 09 '17 at 14:07

3 Answers3

4

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);
}
flyte
  • 1,242
  • 11
  • 18
  • 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 :/ Thanks @flyte – Euridice01 Oct 27 '17 at 16:56
  • That's a strange case - I am not sure. You will have to dig further into Dapper and Dapper.Contrib on how to handle it. Vote and Accept Answer if this post has helped you with your original question. – flyte Oct 27 '17 at 17:12
  • Aw ok. Unfortunately, can't mark it as accepted as I already what you mentioned already setup. It's that issue I mentioned that I'm having trouble with :( I will edit my post to make it clearer. – Euridice01 Oct 27 '17 at 17:18
  • Nope. My post answered your original question of "but I want it to be inserted into a table with a different name than the model". – flyte Oct 27 '17 at 17:51
  • My question apparently was not clear from the beginning, so I edited the title. This is the main issue I've been having, I already know how to do a basic insert with the table attribute. Sorry for the confusion but thanks for making me clarify the post. – Euridice01 Oct 27 '17 at 17:56
  • Hey, I think you have the right idea but I can't get to insert into my table. Also you have some typos in your post. Can I edit the typos? I think maybe the issue is @FooBarObj.Id etc part.... What should FooBarObj be in this scenario? It's really FooBar model I have above right? So it should be FooBar.Id and not myFooBar.Id right? – Euridice01 Oct 27 '17 at 20:04
  • I added a bounty to the question. I'm tripping over: The error I get is: Must declare the scalar variable "@FooBarObj". Do I need the @Object part? Why not just use Id, Foo, Bar etc? What should the format of the latter part be? – Euridice01 Nov 09 '17 at 14:56
1

I think flyte has a good part of the answer and his solution could certainly work, and the Dapper.Contrib project is very useful.

Just to give another solution or at least a slightly different way of looking at it. Firstly I feel that all entities should only represent one table, it will keep things clear in the future in the case the two tables diverge.

So what you might want to try and do is have two classes where the duplicate extends the original (or is a copy of it). Then use a mapper (pick any) when you need to insert the duplicate entry.

[Table("Original")]
public class Original
{
    //properties
}

[Table("Duplicate")]
public class Duplicate : Original
{
    //properties
}

Then when you condition is met.

if (something)
{
    var dup = _mapper.Map<Original, Duplicate>(orig);
    conn.Insert(dup);
}

Hope this helps.

sQuir3l
  • 1,373
  • 7
  • 12
0

You can use EF or PetaPoco

  • My suggestion is PetaPoco because very simple and affective.

if you are dealing with big data then my suggestion

  • EntityFramework

Your object

[TableName("Administrators")]
[PrimaryKey("dbid", autoIncrement = true)]
class Administrators
{
    public int dbid { get; set; }
    public string Name { get; set; }
    public string SurName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
}

Insert statement

var Administrators= new Administrators{ 
Name = "Mami", 
Surname= "Dora" 
};

object getObj= db.Insert(Administrators);

Basic Example (Get&Set)

App.config

 <connectionStrings>
    <add name="PetaExample" connectionString="Data Source=MDORA17\SQLEXPRESS;Initial Catalog=mdblog;Integrated Security=True;Connect Timeout=300;" providerName="System.Data.SqlClient" />
  </connectionStrings>

GET

 static void Main(string[] args)
        {
            using (var db = new Database("PetaExample"))
            {
                try
                {
                    var result = db.Query<Administrators>("select * from mdpub.Administrators").ToList();

                    result.ForEach(ShowPerson);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            Console.ReadKey();
        }

        private static void ShowPerson(Administrators admin)
        {
            Console.WriteLine("{0} {1} ", admin.Name, admin.SurName);
        }

SET

static void Main(string[] args)
        {
            using (var db = new Database("PetaExample"))
            {
                try
                {
                    var Administrators = new Administrators
                    {
                        Name = "Mami",
                        SurName = "Dora",
                    };

                    db.Insert("mdpub.Administrators", "dbid", true, Administrators);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            Console.ReadKey();
        }


    }
    public class Administrators
    {
        public int dbid { get; set; }
        public string Name { get; set; }
        public string SurName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

    }
mdora7
  • 41
  • 1
  • 5