Linq查询EAV设计表

时间:2013-10-31 09:25:41

标签: c# sql linq entity-attribute-value

我有使用EAV设计表的情况,我是这个设计的新手,我对选择查询很震惊。下面是我的查询结构和数据。

TABLE1:
 Id KeyName
 1  Name
 2  Age

TABLE2:
ID  TABLE1_ID VALUE
 1    1        ABC
 2    2        12
 3    1        CDF
 4    2        14    
 5    1        XYZ
 6    2        13
 7    1        CSF
 8    2        10 

EXPECTED OUTPUT: Get all the values which are greater than 12 AND Value contains "C".
i.e., 
  Table2_ID  Result  Table1_KeyName
       1      ABC      Name
       2      12       Age
       3      CDF      Name
       4      14       Age

我尝试过的选项是:

        Var temp = (from c in Table2
                    where c.Value > 12 && c.Table1.KeyName.Contains("C")
                    Select new
                   {
                    ID = c.ID,
                    Result = C.Value
                   }); 

上面的查询没有返回任何结果,因为过滤器(在where子句中)是跨行的。我甚至在where子句中尝试了“OR”条件,它返回了我的一切。请帮帮我。

1 个答案:

答案 0 :(得分:1)

您的查询错误,您是在这里输入还是从工作中复制粘贴?

您是否在ORM(例如Entity Framework)中设置了此表?因此table1和table2之间存在关系设置,所以你不必“加入”它们吗?

要更“正确”,它应该是......

    Var temp = (from c in Table2
                where c.Value > 12 && c.Table1.Name.Contains("C")
                Select new
               {
                ID = c.ID,
                Name = c.Table1.Name,
                Value = c.Value
               });

或者,如果关系不在ORM中,则您使用显式指定连接,如下所示:

    Var temp = (from c in Table2
                join c1 in Table1 on c.Table1_ID equals c1.Id
                where c.Value > 12 && c.Table1.Name.Contains("C")
                Select new
               {
                ID = c.ID,
                Name = c.Table1.Name,
                Value = c.Value
               });

编辑:那么它应该是OR,而不是AND

    Var temp = (from c in Table2
                where c.Value > 12 || c.Value.Contains("C")
                Select new
               {
                ID = c.ID,
                Result = c.Value,
                KeyName = c.Table1.Name
               });