zoukankan      html  css  js  c++  java
  • EntityFramework 1.0 在查询中需要引用子表信息时的子表数据加载处理

    我在执行下列查询时得到一个NullReferenceException:

    var queryResult = from lr in currentClient.LocalRates
        
    where lr.TaxYear == taxYear && lr.TaxType.TaxTypeName == taxTypeName && lr.LocalCode == localCode
        select lr;

    注意,在where部分的红字处,我引用了导航属性的对象的一个属性,但是在默认情况下,EF不会主动加载导航属性的对象,因此 lr.TaxType实际上是一个null,我这么写当然会出错。

    解决方法是,让EF在加载LocalRates的时候,同时加载每个LocalRate的TaxType信息。正如以下代码所示:

    var queryResult = from lr in currentClient.LocalRates.CreateSourceQuery().Include("TaxType")
        
    where lr.TaxYear == taxYear && lr.TaxType.TaxTypeName == taxTypeName && lr.LocalCode == localCode
        select lr;

    利用Include方法,将需要包含的“子表”信息一并加载进来就好了。可以依次使用多次Include方法,将所需的多个子表同时加载进来,即  ObjectQuery.Include("Table1").Include("Table2") 这样的形式。

  • 相关阅读:
    Luogu P5853 [USACO19DEC]Tree Depth P
    Luogu P6009 [USACO20JAN]Non-Decreasing Subsequences P
    HDU6309 Absolute
    Luogu P4734 [BalticOI 2015]Hacker
    Gym102431F Ferry
    Gym102431G Game on the Tree
    AGC018F Two Trees
    Gym102268D Dates
    AGC023F 01 on Tree
    CF700E Cool Slogans
  • 原文地址:https://www.cnblogs.com/Ricky81317/p/1659018.html
Copyright © 2011-2022 走看看