是否可以使用Entity Framework创建动态查询。我有18张桌子,每张桌子都有相同的结构。如何创建动态查询以对每个表重用相同的查询。我想有一个创建读取更新删除的通用查询。 该读取包含相同的“Where”子句。 谢谢你的帮助。
答案 0 :(得分:1)
这里有纯CRUD场景的简单示例。创建将包含查询的共享属性的界面。在所有实体类中实现此接口。比创建存储库。存储库通常被定义为通用的,但在您的情况下,我将每个方法定义为通用的,以便您可以对所有实体使用相同的存储库权限。
public interface IWellKnownEntity
{
int Type { get; set; }
}
public class Repository
{
public T GetEntityByWellKnownQuery<T>() where T : IWellKnownEntity
{
using (var context = new MyContext())
{
return context.CreateObjectSet<T>().FirstOrDefault(e => e.Type == 1);
}
}
public IEnumerable<T> GetEntitiesByCustomQuery<T>(Expression<Func<T, bool>> where)
{
using (var context = new MyContext())
{
return context.CreateObjectSet<T>().Where(where).ToList();
}
}
public void Create<T>(T entity) where T : IWellKnownEntity
{
using (var context = new MyContext())
{
context.AddObject(entity);
context.SaveChanges();
}
}
public void Update<T>(T entity) where T : IWellKnownEntity
{
using (var context = new MyContext())
{
context.Attach(entity);
context.ObjectStateManager.ChageObjecState(entity, EntityState.Modified);
context.SaveChanges();
}
}
public void Delete<T>(T entity) where T : IWellKnownEntity
{
using (var context = new MyContext())
{
context.Attach(entity);
context.DeleteObject(entity);
context.SaveChanges();
}
}
}
比你假设你有实体产品和catebory哪个推动着名的界面。您只需致电:
var repository = new Repository();
var product = repository.GetEntityByWellKnownQuery<Product>();
product.Name = "Updated";
repository.Update<Product>(product);
var category = repository.GetEntitiesByCustomQuery<Category>(c => c.Id == 1).First();
repository.Delete<Category>(category);
您可以进一步改进示例代码。此代码不使用共享上下文,因此它更适用于断开连接的方案(Web应用程序)。如果使用WinForms应用程序或批处理应用程序等连接方案,则可以在存储库上实现IDisposable并在所有方法之间共享上下文。存储库上的Dispose方法将处理上下文。更新和删除方法的代码将有所不同,因为不需要将实体附加回上下文或设置实体状态。