有人帮我将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 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;
}
答案 0 :(得分:1)
试试这个:
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);
}
}
答案 1 :(得分:1)
如果您的“用户”是一个包含用户和报告属性的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();