I have written Linq Query that i wanted to make it Lambda Expression . how to write the Lambda Expression in place of return statement Linq Query . entities tables are entities.Users,entities.Users,entities.ponds
Query Expression :
from pond in Ponds
join customerdevice in CustomerDevices on pond.Imei equals customerdevice.Imei
join user in Users on customerdevice.CustomerId equals user.CustomerId
where user.Username=="user1"
select new { temp = pond.Temp, imei = pond.Imei,timestamp=pond.Timestatmp }
Lambda Expression :
public async Task<IHttpActionResult> GetAllData(int deviceid)
{
using (smartpondEntities entities = new smartpondEntities())
{
try
{
return Ok(await entities.ponds.Where(u=>u.deviceid==deviceid).OrderByDescending(u => u.timestatmp).ToListAsync());
}
catch (Exception Ex)
{
return BadRequest("Sorry Error Found!!!");
}
}
}
That's pretty much a 1-1 mapping.
entities.Ponds
.Join(entities.CustomerDevices, pond => pond.Imei, device => device.Imei, new {pond,device});
.Join(entities.Users, devicePond => devicePond.deviceCustomerId, user => user.CustomerId, new {devicePond.pond, devicePond.device, user})
.Where( e => e.user.Username == "user1")
.Select( e => new { temp = e.pond.Temp, imei = e.pond.Imei,timestamp=e.pond.Timestatmp })
.ToListAsync();
However, I'd suggest you add some navigational properties on your entities to shorten the Linq queries and have EF generate the joins for you.
public class Ponds {
public string Imei {get;set}
[ForeignKey(nameof(Imei))]
public virtual CustomerDevice Device {get;set;}
}
public class CustomerDevices {
[Key]
public string Imei {get;set}
public int CustomerId {get;set;}
public int DeviceId {get;set;}
[ForeignKey(nameof(CustomerId))]
public virtual User Customer {get;set;}
}
public class Users {
[Key]
public int CustomerId {get;set;}
}
Shorting the query to:
this.entites.Ponds.Where (
e => e.Device.Customer.Username == "user1" ||
e.Device.DeviceId == 1
)
.Select( e => new { temp = e.Temp, imei = e.Imei,timestamp=e.Timestatmp })
.FirstOrDefaultAsync();
You should then consider using something like SQLProfiler if you're using a MS DB to view, and then optimize the EF-SQL query.
You lamda should be :
var ponds = from pond in Ponds
join customerdevice in CustomerDevices on pond.Imei equals customerdevice.Imei
join user in Users on customerdevice.CustomerId equals user.CustomerId
where user.Username=="user1"
select new { temp = pond.Temp, imei = pond.Imei,timestamp=pond.Timestatmp }
Then query (I replaced deviceid with imei).
return Ok(await entities.ponds.Where(u=>u.imei==deviceid).OrderByDescending(u => u.timestatmp).ToListAsync());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.