如何使用EF 6的通用模型查询

编程入门 行业动态 更新时间:2024-10-25 11:27:06
本文介绍了如何使用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.

推荐答案

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

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的通用模型查询

本文发布于:2023-11-03 12:27:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555134.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   模型   EF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!