如何使用EF 6的通用模型查询 [英] How to query on a generic model using EF 6

查看:150
本文介绍了如何使用EF 6的通用模型查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个MVC 5应用程序。我在我的数据库查询:

I am developing an MVC 5 application. I query on my database as:

var result = db.ABCs.AsNoTracking().FirstOrDefault(e => e.Id == Id);



但是,如果我想打一个通用的方法,不知道对模型的名称是什么编译时间。我想在传递给方法在运行时的任何模型类查询。
的东西为:

But what if I want to make a generic method and Don't know the name of the model on compile time. I want to query on any model class that is passed to a method at runtime. Something as :

var result = db.<T>.Where(x => x.Id == Id).ToList();



我怎样才能做到这一点。我使用的数据库,第一个办法,也没有仓库或UOW。

How can I do that. I am using database first approach and no repositories or UoW.

推荐答案

要做到这一点,你需要给有关<$一些信息C $ C>编号属性。你可以做到这一点对所有实体的属性创建具有通用接口:

To do this, you need to give some information about Id property. You can do it creating interface with common for all entities properties:

interface IEntity
{
    int Id {get;}
}

而在你的类实现它:

class ABC : IEntity
{
    int Id {get; set;} 
    string Name {get;set;}
}

List<T> GetData<T>(int id) where T : class, IEntity
{
    var result = db.Set<T>().Where(x => x.Id == Id).ToList();
    return result;
}

...

var data = GetData<ABC>(10);

这篇关于如何使用EF 6的通用模型查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆