0

I want to write some entity into database but there are a lot of entities I like to write something generally for them now I know this :

using(var dbContext = new myEntity())
{
   db.EntityName.AddToObject(newEntity);
   db.SubmitChanges();
}

I dont know how I can change it to something like this : db.AddToObject("stringName") I just want to write a few code because I have many tables so I have many entities in my model.

It will be good for me write a method and call it by different names.

kamiar3001
  • 2,646
  • 4
  • 42
  • 78

2 Answers2

1

One simple way would be to encapsulate the insert method into a delegate and pass it to your code like this:

void InsertEntity<TEntity>(TEntity newEntity, Func<myEntity, TEntity> insertCallback) where TEntity : EntityObject
{
    using(var dbContext = new myEntity())
    {
        insertCallback(dbContext, newEntity);
        dbContext.SaveChanges();
    }
}

After that, when inserting an item you'll need to supply the insert method (assuming you have an entity called Client) :

var client = new Client();
InsertEntity<Client>(client, (dbContext, entity) => dbContext.Client.AddToObject(entity));
RePierre
  • 9,358
  • 2
  • 20
  • 37
0

ScottGu has a Dynamic Linq library you can use.

enter image description here

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • I have download it but I couldn't implement my goals could you help me more? I mean show me how I can implement this? – kamiar3001 Apr 23 '12 at 16:49
  • I haven't worked with it personally, sorry. I just know that it is the right tool to use in situations like this. Generally speaking, you should only use "magic strings" under certain "special" conditions if your program architecture or requirements demand it; your situation may not qualify as special in this regard. – Robert Harvey Apr 23 '12 at 16:50
  • you know I study this but the problem is the name of entity actually the main name is not dynamic its condition is dynamic it is very useful but I need something more I need this one and dynamic entity name because if you have many entities you need more capabilities. – kamiar3001 Apr 23 '12 at 17:49
  • The bottom line: dynamic linq is about querying not inserting. – Gert Arnold Apr 27 '12 at 20:43
  • @Gert: Ah, quite right. I totally missed that. – Robert Harvey Apr 27 '12 at 20:44