动态 SQL 到 LINQ 实体框架
Posted
技术标签:
【中文标题】动态 SQL 到 LINQ 实体框架【英文标题】:Dynamic SQL to LINQ Entity Framework 【发布时间】:2016-10-01 02:48:03 【问题描述】:我只有 LINQ 的基础知识。我讲 SQL 和 JDBC,负责将动态 PL/SQL 转换为 LINQ 实体框架。如何将条件 WHERE 子句添加到 LINQ 查询中?这是一个非常简化的示例(省略类型信息):
Q1 := 'SELECT bDay = b.birthday
address = b.address
FROM (' ;
Q2 := 'SELECT folks.birthday, Address.address
FROM folks,
(SELECT state,
surname AS name
FROM Individuals, Addresses
WHERE Individuals.addrId = Address.id
AND Addresses.state = 'CA' ) find1
,(SELECT state,
surname AS name
FROM Individuals, Addresses
WHERE Individuals.addrId = Address.id
AND Addresses.state = 'NV' ) find2
AND find1.state(+) = folks.state';
IF input_parm = 'RED' THEN
condAddOn :=condAddOn || 'AND folks.vacationHouse IS NOT NULL';
END IF;
IF input_parm = 'BLUE' THEN
condAddOn :=condAddOn || 'AND folks.vacationHouse = 'Cabin';
END IF;
...
OPEN curs FOR Q1 || Q2 || condAddOn ')b';
试图弄清楚 C#/LINQ 语法,这是我的尝试(自下而上):
var find1 = (from addr in Addresses
from indiv in Individuals
where indiv.addrId = addr.addrID
select new
indiv.state,
indiv.surname
);
var find1OuterJoin = (from person in folks
join f1 in find1 on person.addrId equals f1.addrID
from f1OutJn in temp.DefaultIfEmpty()
select new
f1OutJn.state,
f1OutJn.surname
);
var Q2 = (from person in folks
from addr in addresses
from f1 in find1OuterJoin
where person.addrId == addr.addrId
&& f1.state == folks.state
select new
person.birthday
,addr.address
);
var Q1 = (from q2 in Q1
select new
bDay = b.birthday
,address = b.address
);
我不知道 1)如果我正确地将 Q1 引入 Q2 2)如何引入动态WHERE子句 以等效的游标语句结束:
OPEN curs FOR Q1 || Q2 || condAddOn ')b';
补充:我可以使用函数或表达式来包含动态位吗?我看到了对 Expression 和 Expandable() 的引用,但不确定。 补充:我对 LINQ 查询的尝试
【问题讨论】:
【参考方案1】:当使用带有链接的where
方法时,您将返回一个IQueryable
对象。这不会立即执行语句,因此可以执行以下操作:
var results = from person in folks
join addr in addresses
where person.addrId == addr.addrId
select new
person.birthday,
addr.address
;
if(predicate)
results = from r in results
where /* new condition here */
select r;
var resultSet = results.ToList().AsEnumerable();
对于其他链接运算符,尤其是在使用 lambda linq 时,您还可以使用 AsQuerably
扩展方法。
例如但不限于:
var results = folks.join(address,
person => person.addrId,
addr => addr.addrId
(person, addr) => new
person.birthday,
addr.address
).AsQueryable();
if(predicate)
results = results.where(/*predicate for the where condition*/);
var resultSet = results.ToList().AsEnumerable();
【讨论】:
感谢您的解释。我想它会让我开始:-)以上是关于动态 SQL 到 LINQ 实体框架的主要内容,如果未能解决你的问题,请参考以下文章
实体框架/LINQ/SQL 与实体框架/LINQ/MYSQL