How can I use dynamic linq to make the insert technique more flexible?

c# dynamic-linq entity-framework

Question

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.

1
0
4/23/2012 4:42:12 PM

Accepted Answer

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));
1
4/24/2012 1:59:10 PM

Popular Answer

ScottGu has a Dynamic Linq library you can use.

enter image description here



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow