EF 4.0 LINQ一对多/多对一

时间:2011-01-11 18:07:41

标签: entity-framework many-to-one one-to-many

刚开始使用LINQ以及EF。

我在以下配置中有一组表:

PublicUtility(UtilityCode)* ----> 1(UtilityCode)实用程序(UtilityCode)1 -----> *(UtilityCode)UtilityDetail

我在SQL中有一个查询。根据其他一些业务规则,此查询将返回1值或NULL。

选择
@UtilityCode = UtilityDetail.UtilityCode

UtilityDetail
INNER JOIN PublicUtility ON     PublicUtility.SubdivisionCode = @SubdivisionCode AND
    PublicUtility.Year = @PublicUtilityYear AND
    PublicUtility.UtilityCode = UtilityDetail.UtilityCode
WHERE
UtilityDetail.DebtPurposeCode = @DebtPurposeCode

我如何使用LINQ to entities重写这个?

1 个答案:

答案 0 :(得分:0)

using (YourObjectContext ctx = new YourObjectContext())
{
    var code = (from ud in ctx.UtilityDetails
                join pu in PublicUtility on ud.UtilityCode equals pu.UtilityCode
                where ud.DeptPurposeCode == [code_value] && pu.SubdivisionCode == [subdivcode_value] && pu.Year == [year_value]
                select new {ud.UtilityCode}).FirstOrDefault();
}