我如何在dbcontext.set中使用where条件< tentity>() [英] How can I use where condition in dbcontext.set<tentity>()

查看:859
本文介绍了我如何在dbcontext.set中使用where条件< tentity>()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在MVC中使用Edit进行多项选择。所以我做了一个Jsonresult来获取该ID的数据: -



我尝试过的事情:



I want to use Edit in MVC for multiple selection . So I've made a Jsonresult to fetch the Data for that Id :-

What I have tried:

<pre>public JsonResult FetchDataForEdit()
        {
            int IDtoEdit = Convert.ToInt32(TempData["IDtoEdit"]);
            string MyTableName = Convert.ToString(TempData["MyTableName"]);
            
            try
            {
                Type tableType = typeof(CourseDesc);
                switch (MyTableName)
                {
                    case "CourseTbl":
                        tableType = typeof(CourseTbl);
                        break;
                    case "CourseDescTbl":
                        tableType = typeof(CourseDesc);
                        break;
                    case "CourseSubDesc":
                        tableType = typeof(CourseSubDesc);
                        break;
                    case "InternTbl":
                        tableType = typeof(InternShip);
                        break;
                    case "ContactTbl":
                        tableType = typeof(Contact);
                        break;
                }

                using (EBContext db = new EBContext())
                {
                    var results = new List<object>();
                    foreach (var item in db.Set(tableType))
                    {
                        //Want to Add result for selected IDtoEdit here
                        results.Add(item);
                    }

                    return new JsonResult { Data = results, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                }

            }

            catch (Exception ex)
            {
                string innerMessage = (ex.InnerException != null) ? ex.InnerException.Message : "";
                return new JsonResult { Data = "Not Found", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }

        }

推荐答案

假设 IDtoEdit 是实体的主键,你只想返回匹配的项目,使用查找

Assuming the IDtoEdit is the primary key of the entity, and you only want to return the matching item, use Find:
using (var db = new EBContext())
{
    var results = new List<object>();
    var item = db.Set(tableType).Find(IDtoEdit);
    if (item != null) results.Add(item);
    
    return Json(results, JsonRequestBehavior.AllowGet);
}



DbSet.Find方法(Object [])(System.Data.Entity) [ ^ ]


这篇关于我如何在dbcontext.set中使用where条件&lt; tentity&gt;()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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