首页 新闻 会员 周边

ef、linq怎么实现JOIN功能

0
悬赏园豆:5 [已解决问题] 解决于 2012-07-31 16:07

ef、linq怎么实现以下的功能

str sqlstr="select a.* from a"
if (code1!="")
sqlstr=sqlstr+" join b on a.id=b.id && b.code=code1"
if (code2!="")
sqlstr=sqlstr+" join c on a.id=c.id && c.code=code1"

问题补充:

在SQL Server Management Studio里直接运行

select distinct(s.Title) from Table1 as si
join Table2 as t on SUBSTRING(t.Code,1,12)='010101010108' and t.tid=si.tid
join ST as st on SUBSTRING(st.Code,1,4)='0104' and st.stid=si.stid
join S as s on SUBSTRING(s.SpellTitle,1,1)='C' and si.sid=s.sid
where si.IsAudited='true' and si.IsDeleted='false' and si.IsVisable='true'

第一次150ms,接下来都是50ms以下。

但是在代码里

            IEnumerable<SI> list = _dataContext.SI.Where(a =>
                (filterModel == 1 ? a.IsAudited == true && a.IsDeleted == false && a.IsVisable == true : a.IsDeleted == false) &&
                (Code == "" ? true : a.ST.Code.StartsWith(Code)) &&
                (tid== 0 ? true : a.tid== tid)).Distinct(....);

最少都在500ms以上,更甚的是,用老外的PredicateBuilder构建表达式,最少都在1.5m左右,这样明显有哪里做得不好.

BorgChen的主页 BorgChen | 初学一级 | 园豆:11
提问于:2012-07-25 09:17
< >
分享
最佳答案
0

你会写这个SQL语句吗?如果会的话,请使用Linqer工具,可以从SQL语句转成LINQ形式~

收获园豆:5
Superman111 | 菜鸟二级 |园豆:215 | 2012-07-25 10:55

会啊,就是手动写了试一下才发现差距那么大。。。我试一下

BorgChen | 园豆:11 (初学一级) | 2012-07-25 10:59

@BorgChen: 肯定是有差距的!

Superman111 | 园豆:215 (菜鸟二级) | 2012-07-25 11:07

@cheersun2010: 主要是太大,本地500+ms传到主机1000+,数据加载明显有停顿感。

join t in _dataContext.T
      on new { t.Code.Substring(1 -1 , 12), tid= (Int32)si.tid}
  equals new { "010101010108", t.tid}
生成的子句里,红字部分提示错误,

无效的匿名类型成员声明符。匿名类型成员必须使用赋值、简单名称或成员访问来声明

求指教!

BorgChen | 园豆:11 (初学一级) | 2012-07-25 11:38
其他回答(2)
0
artwl | 园豆:16736 (专家六级) | 2012-07-25 09:57

这个已经看过了,不适用的。一个是要复合属性,再要动态拼接。

好像on有这种写法,on new{a.id,a.other} equals new {b.id,b.other},也有人写做on new{k1=a.id,k2=a.other} equals new {k1=b.id,k2=b.other},但不知道具体细化到我这个例子怎么写,不只是两表相关字段的匹配,其中一个k2=code1?

支持(0) 反对(0) BorgChen | 园豆:11 (初学一级) | 2012-07-25 10:16
0

var query = from s in test.BS_Roster
                        join c
in test.BS_CLASS
                        on  s.rid
= c.rid
                        
select s ;

jerry-Tom | 园豆:4077 (老鸟四级) | 2012-07-25 10:17
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册