简体   繁体   English

如何使用linq C#使用实体框架获取两个表合并记录?

[英]how to get two table combine record using entity framework with linq c#?

I want to get two table combine data using linq c# lambda expression and get fix number of column get in the list. 我想使用linq c#lambda表达式获取两个表合并数据,并获取列表中列的固定编号。 I have try this code but I don't know how to write query in linq lambda expression. 我已经尝试过此代码,但是我不知道如何在linq lambda表达式中编写查询。

this is my method: 这是我的方法:

public ActionResult GetUserList(string searchRequest)
{          
    List<User> userList = new List<User>();              
    if (searchRequest != null)
    {
        if (searchRequest == "All")
        {
// here i want to write select query but how i don't know
            userList = db.user.ToList();
        }
        else if (searchRequest == "Flight") 
        {
            userList = db.user
                .Where(t => t.type_id == (int)ServiceTypeEnum.Flight)
                .ToList();
        }                   
    }                                       
    return Json(new { data = userList });
}

any one have the idea about this query then please let me know how can do. 任何人都对此查询有想法,那么请让我知道该怎么做。

Define UserDto class for columns that you want select 为要选择的列定义UserDto类

public class UserDto
{
    public int Id{get;set;}

    public int Name{get;set;}

    //Other Properties
}

Then change your code to following 然后将您的代码更改为以下内容

public ActionResult GetUserList(string searchRequest)
{
    try
    {                            
        if (searchRequest != null)
        {
            IQueryable<User> query; 

            if (searchRequest == "All")
            {
                query = db.user.AsQueryable(); // here i want to write select query but how i don't know
            }
            else if (searchRequest == "Flight") 
            {
                UserList = db.user.Where(t => t.type_id == (int)ServiceTypeEnum.Flight);
            }  

            if(query != null)
            {
                var list = query.Select(e=> new UserDto
                {
                    Id = e.Id,
                    Name = e.Name
                    //Other properties
                }).ToList();

                return Json(new { data = list });
            }   
        }                                       

   }
   catch (Exception ex)
   {
       throw;
   }
   return Json(null);
}

The issue that you will experience with lambdas where you select specific fields is that the result is normally an anonymous type. 您在选择特定字段的lambda上会遇到的问题是,结果通常是匿名类型。 Anonymous types from two different queries cannot easily be joined together in a list because the compiler cannot verify the structure or equality of the types. 由于编译器无法验证类型的结构或相等性,因此无法轻松地将来自两个不同查询的匿名类型连接到一个列表中。

There are other ways around this... 还有其他解决方法...

The best practice approach is to create a formal type definition and use that so that you can manipulate your objects outside of your lambda expressions. 最佳实践方法是创建一个正式的类型定义并使用它,以便您可以在lambda表达式之外操作对象。 Note here that I have assumed a simple example structure that is a sub-set of user: 注意这里我假设一个简单的示例结构是用户的子集:

public ActionResult GetUserList(string searchRequest)
{
    try
    {
        List<UserSearchResult> UserList = new List<UserSearchResult>();
        if (searchRequest != null)
        {
            if (searchRequest == "All")
            {
                UserList.AddRange(db.user.Select(u => new UserSearchResult { Title = u.Title, FirstName = u.Firstname, LastName = u.Lastname })); // here i want to write select query but how i don't know
            }
            else if (searchRequest == "Flight")
            {
                UserList.AddRange(db.user.Where(t => t.type_id == (int)ServiceTypeEnum.Flight)
                    .Select(u => new UserSearchResult { Title = u.Title, FirstName = u.Firstname, LastName = u.Lastname }));
            }
        }
        return Json(new { data = UserList });
    }
    catch (Exception ex)
    {
        throw;
    }
    return Json(null);
}

public class UserSearchResult
{
    public string Title { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Because we have explicitly cast the result of our selection of specific fields to a formal type, we can now use that type in operations outside of your queries and can even manipulate the values. 因为我们已经将选择特定字段的结果显式转换为形式类型,所以我们现在可以在查询之外的操作中使用该类型,甚至可以操纵值。

I think the local variable is holding you back. 我认为局部变量阻碍了您。 Just return the result you want. 只需返回您想要的结果。

public ActionResult GetUserList(string searchRequest)
{
    if (searchRequest == "All")
    {
       var users = db.user
           .Select(user => new {user.Name, user.Address.ZipCode})
           .ToList();

       return ToJson(users);
    }
    else if (searchRequest == "Flight") 
    {
        List<User> users = db.user
            .Where(t => t.type_id == (int)ServiceTypeEnum.Flight)
            .ToList();

        return ToJson(users);
    }

    return ToJson(new List<User>());
}

private ActionResult ToJson<T>(T list)
{
    return Json(new { data = list });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用linq和C#中的实体框架从另一个表中获取对象中的项目列表? - how to get a list of item in object from another table using linq and entity framework in C#? C#,LInq,实体框架4:使用Linq将表拆分为二维数组 - C#, LInq, Entity Framework 4: Split a table in to a two dimensional array using Linq 如何使用 LINQ 获取最后一条记录 - SQLite 中的实体框架 - How to Get Last Record Using LINQ - Entity Framework in SQLite 使用 C# 实体框架在临时表中插入记录 - Insert Record in Temporal Table using C# Entity Framework 从数据库获取所有表,并使用C#,Linq查询和Entity Framework遍历每个表 - Get all tables from database and loop through each table using C#, Linq query and Entity Framework 如何使用Linq组合两个c#对象 - How to combine two c# objects using Linq 如何使用Linq和C#在实体框架中获取多个结果集? - How to get Multiple Result Set in Entity Framework using Linq with C#? 如何使用C#实体框架删除数据库记录? - How to delete a database record using c# entity framework? 如何通过使用linq C#比较两个列表来获取更新的记录 - How to get the updated record by comparing two list using linq C# 如何使用实体框架在C#,ASP.NET MVC 3中的两个日期之间获取记录? - How to get records between two dates in C#, ASP.NET MVC 3 using Entity Framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM