如何使用动态linq使插入方法更灵活?

时间:2012-04-23 16:42:12

标签: c# entity-framework dynamic-linq

我想将一些实体写入数据库,但是我现在有很多实体想要为他们写一些东西我现在知道了:

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

我不知道如何将其更改为:db.AddToObject(“stringName”)我只想编写一些代码,因为我有很多表,所以我的模型中有很多实体。

我会写一个方法并用不同的名字来调用它。

2 个答案:

答案 0 :(得分:1)

一种简单的方法是将insert方法封装到委托中并将其传递给您的代码,如下所示:

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

之后,在插入项目时,您需要提供insert方法(假设您有一个名为Client的实体):

var client = new Client();
InsertEntity<Client>(client, (dbContext, entity) => dbContext.Client.AddToObject(entity));

答案 1 :(得分:0)

ScottGu有一个Dynamic Linq库你可以使用。

enter image description here