我想要的是:
DataTable dt=mystaticClass.gettableFuction("select col1,col2,col3,col4 from table1 where date between (date1 and date2) and id=(select max(id) from table1)");
现在我希望使用linq表达式填充数据表。我试过这个。
lamiEntities1 lam = new lamiEntities1();
var pay = from p in lam.Mytablename.AsEnumerable()
where p.Date > start && p.Date < end
select new
{
Column1 = p.col1,
Column2 = p.col2
Column3 = p.col2
Column4 = p.col2
};
这里不知道如何调用max函数来获取max(Id)
grid1.datasource = pay;
这里我只得到一个column1值,而不是整行有4列
如果我删除
select new
{
Column1 = p.col1,
Column2 = p.col2
Column3 = p.col2
Column4 = p.col2
};
并将其更改为
select p;
我得到了所有不需要的列,包括我的4列。
我正在使用Mysql和Entity Framework 6.1.3。
答案 0 :(得分:2)
我想,你需要,
。只需在select new中的列之间使用,
:如果您尝试这样,则第一个解决方案将起作用。
lamiEntities1 lam = new lamiEntities1();
var pay = from p in lam.Mytablename.AsEnumerable()
where p.Date > start && p.Date < end
select new
{
Column1 = p.col1,
Column2 = p.col2,
Column3 = p.col2,
Column4 = p.col2,
};
答案 1 :(得分:1)
您可以使用let
表达式来存储表中的最大ID,如下所示: -
var pay = from p in lam.Mytablename.AsEnumerable()
let maxid = lam.Mytablename.AsEnumerable().Max(x => x.Field<int>("Id"))
where p.Date > start && p.Date < end && p.Field<int>("id") == maxid
select new
{
Column1 = p.col1,
Column2 = p.col2,
Column3 = p.col2,
Column4 = p.col2
};
作为旁注,我认为你不会直接从DataTable获得这样的p.col1
属性(我想你已经证明了这一点),检索值的好方法是{{1正如我在比较id时所做的那样。
答案 2 :(得分:1)
据我所知,您正在搜索以下SQL查询的LINQ等价物
select col1,col2,col3 from table1 where date between (date1 and date2) and id=(select max(id) from table1)
首先,让SQL查询更具可读性
select t.col1, t.col2, t.col3
from table1 as t
where t.date between (startDate and endDate)
and id=(select max(t1.id) from table1 as t1)
然后将其翻译为LINQ
var query =
from t in db.table1
where t.date >= startDate && t.date <= endDate
&& t.id == db.table1.Max(t1 => t1.id)
select new { t.col1, t.col2, t.col3, t.col4 };
正如您所看到的,在这种情况下,它几乎是一对一的映射。
答案 3 :(得分:1)
var abc = (from q in lam.Mytablename.AsEnumerable()
where q.Id == (from p in lam.Mytablename.AsEnumerable() select p).Max(x => x.Id)
&& q.Date > start && q.Date < end
select new
{
Column1 = p.col1,
Column2 = p.col2,
Column3 = p.col2,
Column4 = p.col2
});