如何使用C#Linq在2个不同的表中获取2个不同的值 [英] How to get 2 different values in 2 different tables using c# linq

查看:86
本文介绍了如何使用C#Linq在2个不同的表中获取2个不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有datagridview的c#程序 我想使用linq在2个不同的表中获取值 我知道我可以使用sql server存储过程来实现 但是我想在linq中这样做,所以我不需要更新数据库

I have a c# program which has a datagridview I want to get values in 2 different tables using linq I know I can achieved this using sql server stored procedure But I want to do it in linq so I do not need to update database

这里是我的代码:

public List<InsuranceHeader> GetInsuranceList(int InsuranceHeaderId) 
{
    var getData =(from item in context.InsuranceHeader 
                  join item2 in context.InsuranceDetail
                  on item.InsuranceHeaderId equals item2.InsuranceDetailId
                  where item.InsuranceHeaderId == InsuranceHeaderId
                  select item).ToList();

    return getData;
}

另一个问题是当我在InsuranceDetail中返回值时,系统抛出错误 因为我知道我将返回类型分配为List(InsuranceHeader)仍然存在 为了达成这个?对不起,我的英语水平

The other problem is when im returning a value in InsuranceDetail The system throws an error because I know that I assigned my return type as a List(InsuranceHeader) is there anyway to achieve this? sorry for my english

推荐答案

您必须为其创建一个新类,因为方法无法返回 Anonymous 类型.

You have to create a new class for it, because a method cannot return an Anonymous type.

喜欢:

public class InsuranceWithDetail
{
    public InsuranceHeader InsuranceHeader { get; set; }
    public InsuranceDetail InsuranceDetail { get; set; }
}

public IEnumerable<InsuranceWithDetail> GetInsuranceList(int InsuranceHeaderId) 
{
    var results = from item in context.InsuranceHeader 
                  join item2 in context.InsuranceDetail
                     on item.InsuranceHeaderId equals item2.InsuranceDetailId
                  where item.InsuranceHeaderId == InsuranceHeaderId
                  select new InsuranceWithDetail 
                  { 
                      InsuranceHeader = item, 
                      InsuranceDetail = item2 
                  };

    // storing the results in a variable, will help on debugging. (quick watch)
    return results;
}

我也将返回IEnumerable,因为查询仅在需要时执行. ToList()将迭代所有项.如果仅请求GetInsuranceList(1).FirstOfDefault(),则仅执行第一迭代. (除非您使用orderby等.)

Also i would return an IEnumerable, because then the query is only executed on demand. The ToList() will iterate all items. If you only request GetInsuranceList(1).FirstOfDefault() only the first iteration is executed. (unless you use orderby etc.)

这篇关于如何使用C#Linq在2个不同的表中获取2个不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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