我使用linq来查询来自数据库的反向记录的sql查询。 我使用查询来绑定gridview。
protected void grdBind()
{
try
{
EventManagerDataContext db = new EventManagerDataContext();
var z = (from x in db.EMR_EVENTs
join y in db.EMR_CLIENTs on x.ClientID equals y.ClientID
where y.ClientID==x.EventID
select x.EventID).Count();
var q = from a in db.EMR_CLIENTs
join b in db.EMR_EVENTs on a.ClientID equals b.ClientID
join c in db.EMR_ACCOUNTs on a.ClientID equals c.ClientID
join d in db.EMR_SUBSCRIPTIONs on c.Account_ID equals d.Account_ID
join f in db.EMR_SUBSCRIPTION_KINDs on d.Subscription_kind_ID equals f.Subscription_kind_ID
select new
{
Customer = a.Name,
Events = z,
TurnOver = f.Monthly_Fee,
StartDate = d.Start_Date,
EndDate = d.End_Date,
CreteDate = d.Create_Date,
ClientID = a.ClientID,
EventID = b.EventID,
SubscriptionID = d.Subscription_ID,
Subscription_kind_ID=f.Subscription_kind_ID,
Account_ID=c.Account_ID,
};
grid.DataSource = q.ToList();
grid.PageSize = int.Parse(drpPageSize.SelectedValue);
grid.DataBind();
}
catch
{
throw;
}
}
我收到了这个输出,
我收到此查询的输出,但我不想要此输出, 我想要这样的输出。
客户名称 活动
ketan 18
monika 12
和其他记录等等意味着我在这里收到9次客户名称并且他创建了事件,但我只想要一些事件和客户名称
意味着我只想要一个客户端名称和事件总数,我是linq to sql的新手。 那么代码中的变化是什么??
答案 0 :(得分:1)
当您在查询中使用连接语法时,您不需要使用'where' 然后将您的查询更改为:
var z = (from x in db.EMR_EVENTs
join y in db.EMR_CLIENTs on x.ClientID equals y.ClientID
select x.EventID).Count();
答案 1 :(得分:1)
我找到了解决方案。here
也可以使用。useful link
这是我的解决方案。
EventManagerDataContext db = new EventManagerDataContext();
var q = from a in db.EMR_CLIENTs
join b in db.EMR_EVENTs on a.ClientID equals b.ClientID into z
join c in db.EMR_ACCOUNTs on a.ClientID equals c.ClientID
join d in db.EMR_SUBSCRIPTIONs on c.Account_ID equals d.Account_ID
join f in db.EMR_SUBSCRIPTION_KINDs on d.Subscription_kind_ID equals f.Subscription_kind_ID
select new
{
Customer = a.Name,
Events =z.Where(b =>b.ClientID==a.ClientID).Count(),
TurnOver = f.Monthly_Fee,
StartDate = d.Start_Date,
EndDate = d.End_Date,
CreteDate = d.Create_Date,
ClientID = a.ClientID,
SubscriptionID = d.Subscription_ID,
Subscription_kind_ID=f.Subscription_kind_ID,
Account_ID=c.Account_ID,
};
grid.DataSource = q.ToList();