C# 将SQL转换为LINQ查询
有人帮我把sql查询转换成linq吗C# 将SQL转换为LINQ查询,c#,linq,C#,Linq,有人帮我把sql查询转换成linq吗 select * from user b,report t where b.Id = t.userid and b.report=1; 我尝试了下面的查询,但不知道如何获取报表表数据并将其绑定到用户类中 public IEnumerable<user> getusers(int reportId) { var users= new List<user>(); using (var db = new DataCont
select * from user b,report t where b.Id = t.userid and b.report=1;
我尝试了下面的查询,但不知道如何获取报表表数据并将其绑定到用户类中
public IEnumerable<user> getusers(int reportId)
{
var users= new List<user>();
using (var db = new DataContext())
{
var Users = (from b in db.user
join t in db.report on b.Id equals t.userid
where b.reportId == reportId
select new {user = db.user,report= db.report}).ToList();
foreach (var myuser in Users)
{
foreach (var cust in myuser.user)
{
var newuser = new user
{
Id = cust.Id,
Address = cust.Adress,
City = cust.Ort,
CustomerIncident = cust.CustomerIncident,
DeliveryAddress1 = cust.Levadress1,
DeliveryAddress2 = cust.Levadress2,
Email = cust.Email,
//I need to get this from the report table
//ReportId = report.id,
//ReportPerson = report.person
};
users.Add(newuser);
}
}
}
return users;
}
public IEnumerable getusers(int-reportId)
{
var users=新列表();
使用(var db=new DataContext())
{
var Users=(来自db.user中的b
在db.report中加入t。Id等于t.userid
其中b.reportId==reportId
选择new{user=db.user,report=db.report}).ToList();
foreach(用户中的var myuser)
{
foreach(myuser.user中的var cust)
{
var newuser=新用户
{
Id=客户Id,
地址=客户地址,
城市=客户,
CustomerIncident=cust.CustomerIncident,
交货地址1=客户地址1,
交货地址2=客户地址2,
电子邮件=客户电子邮件,
//我需要从报告表中得到这个
//ReportId=report.id,
//ReportPerson=report.person
};
users.Add(newuser);
}
}
}
返回用户;
}
试试这个:
var users = from u in db.user
join r in db.report
on u.Id equals r.userid
where u.reportId == reportId
select new
{
User = u,
Report = r
};
foreach (var user in users)
{
foreach (var cust in myuser.user)
{
var newUser = new user
{
Id = cust.Id,
Address = cust.Adress,
City = cust.Ort,
CustomerIncident = cust.CustomerIncident,
DeliveryAddress1 = cust.Levadress1,
DeliveryAddress2 = cust.Levadress2,
Email = cust.Email,
ReportId = user.Report.report.id,
ReportPerson = user.Report.report.person
};
users.Add(newUser);
}
}
如果“用户”是一个同时保存用户和报表属性的viewmodel,则可以在单个查询中获得所需的所有内容,而无需循环
var users = (from u in db.user
join r in db.report on u.Id equals r.userid
where u.reportId == reportId
select new user
{
Id = u.Id,
Address = u.Adress,
City = u.Ort,
CustomerIncident = u.CustomerIncident,
DeliveryAddress1 = u.Levadress1,
DeliveryAddress2 = u.Levadress2,
Email = u.Email,
ReportId = r.id,
ReportPerson = r.person
}).ToList();