LINQ Query - How i can make my query better? - linq

I have written following LINQ query to return list and then iterating list separately to convert time into hours and taking sum of hours for each list item.
I am sure this might not be the right away as it send three database calls.
Can i re-write it in a better way e.g. GroupBy or by some other way to assign data to model, converting IdleTime into hours and than taking sum of IdleTime??
Model Class
public class TestModel
{
public string TaskSummary { get; set; }
public string LocationName { get; set; }
public float IdleTime { get; set; }
public string Description { get; set; }
public float IdleTimeSum { get; set; }
public Guid TaskId { get; set; }
}
LINQ Query
List<TestModel> list = _context.Time
.Include(x => x.Report)
.Include(x => x.Report.Task)
.Include(x => x.Report.Task.Location)
.Where(x => taskIds.Contains(x.Report.TaskId))
.Select(x => new TestModel
{
TaskSummary = x.Report.Task.Summary,
LocationName = x.Report.Task.Location.Name,
IdleTime = x.Duration,
Description = x.Description,
TaskId = x.Report.TaskId,
}).ToList();
How i am converting into hours?
foreach (var item in list)
item.IdleTime = item. IdleTime / 60;
How I am taking sum?
foreach (var item in list)
item.IdleTimeSum = item. IdleTime;

Just add those to your projection:
.Select(x => new TestModel
{
TaskSummary = x.Report.Task.Summary,
LocationName = x.Report.Task.Location.Name,
IdleTime = x.Duration / 60.0f,
Description = x.Description,
TaskId = x.Report.TaskId,
NPTHoursSum = x.Duration / 60.0f,
}).ToList();
Although since you're not showing where you actually sum anything I suspect there's more to the problem than that.

Yeah Select is a projection function, you can just do those operations in your select.
.Select(x => new TestModel
{
TaskSummary = x.Report.Task.Summary,
LocationName = x.Report.Task.Location.Name,
IdleTime = x.Duration /60.0f,
NPTHoursSum = x.Duration / 60.0f,
Description = x.Description,
TaskId = x.Report.TaskId,
}).ToList();
If you're using LINQ to SQL then the division operation will probably occur at the db. If you actually want to do a sum it would have to be in a different query or as a sub query or something.\

Related

How to write more efficient linq to entities query using EF6

I have an one-to-many relation in my entities:
public class Header
{
public Header()
{
Items = new List<Item>
}
public int Id {get; set;}
public virtual ICollection<Item> Items {get; set;}
// other properties
}
public class Item
{
public int Id {get; set;}
public virtual Header Header { get; set; }
public string Title { get; set; }
public DateTime CreationDate { get; set; }
public int Weight { get; set; }
}
I want to load Header and some of its Items, so I wrote this linq to entity query(EF6):
using(var ctx = new MyContext())
{
var result = ctx.Headers.Where(someConditions)
.AsNoTracking()
.Select(header => new {
HeaderId = header.Id,
//fetch other header properties here
LastItemCreationDate = header.Items.OrderByDescending(item => item.CreationDate)
.Select(item => item.Title)
.FirstOrDefault(),
LastItemTitle = header.Items.OrderByDescending(item => item.CreationDate)
.Select(item => item.CreationDate)
.FirstOrDefault(),
LastItemWeight = header.Items.OrderByDescending(item => item.CreationDate)
.Select(item => item.Weight)
.FirstOrDefault()
}).ToList();
}
This query generate a sql script with 3 times join Header and Item tables, is there any more efficent way to write this query to join Header and Item tables one time?
Since you are using Select, you don't need AsNoTracking since the resulting query will not load any entities. The key performance impacts in your case would be indexes in the Header table suitability for your Where clause, then also whether there is a Descending Index available on the CreationDate in the Items table.
Another improvement would be to alter the projection slightly:
var result = ctx.Headers.Where(someConditions)
.Select(header => new {
HeaderId = header.Id,
LatestItem = header.Items
.OrderByDescending(item => item.CreatedDate)
.Select(item => new
{
Title = item.Title,
CreationDate = item.CreationDate,
Weight = item.Weight
}).FirstOrDefault()
}).ToList();
This will change the resulting anonymous type structure a bit, but should result in a nicer, single join.
You will get a result.HeaderId, then a null-able result.LastestItem containing the latest item's properties. So result.LatestItem?.Title instead of result.Title.

LINQ Lazy load or query incorrect

LINQ Query not populating
Model extract is as follows
public class ServiceBulletin
{
[Key]
public int Id { get; set; }
public virtual ICollection<ServiceBulletinProducts> ApplicableProducts { get; set; }
}
public class ServiceBulletinProducts
{
[Key]
public int Id { get; set; }
public int ServiceBulletinId { get; set; }
public virtual Product Product{ get; set; }
}
I'm using the following code at the moment to populate a collection
var x = from m in _dc.ServiceBulletins.Include(p => p.ApplicableProducts)
.Include(m => m.Manufacturer)
where m.DeleteStatus == DeleteStatus.Active
select m;
var x1 = new List<ServiceBulletin>();
foreach (var item in x)
{
var p = from m1 in _dc.ServiceBulletinsProducts.Include(p2=>p2.Product)
where m1.Product.DeleteStatus == DeleteStatus.Active &&
m1.ServiceBulletinId == item.Id
select m1;
var p99 = p.ToList();
item.ApplicableProducts = p99;
x1.Add(item);
};
So this is intended to have a Parent Child relationship and I’m trying to do a query which populates a collection of ServiceBulletins with a ApplicableProducts item with a fully populated collection of ServiceBulletinProducts for the ServiceBulletin with the values of the Product populated
The collection is populated but the ServiceBulletinProducts are always set to null and I can’t seem to add an Include such as .Include(p => p.ApplicableProducts.Products) to try and populate the product details – which is resulting in me iterating around the collection to populate the items.
Am I missing something to enable the population on the 1st query for the Include statement or do I need to do the query in a different way ?
Figured out the following should do the trick.
var x = from m in _dc.ServiceBulletins.Include(p => p.ApplicableProducts.Select(p2=>p2.Product))
.Include(m => m.Manufacturer)
where m.DeleteStatus == DeleteStatus.Active
select m;

Concatenate Datetime and string and bind result to dropdownlist using Json method

I want to concatenate DateTime field and string field in MVC application.
I want Linq to Entities query to solve this. Here is my SQL query which I want in Linq.
Select accountid,TourID, ' ('+ convert(nvarchar(20), fromdate ,105) +')' + purpose as TourDetails
from Tour
where AccountID=#AccID;
As shown in above query I want to concat fromdate and purpose. I want to pass result of this query as JSON result.
Something like this:
public class Tour
{
public int accountid { get; set; }
public int TourID { get; set; }
public DateTime date { get; set; }
public string purpose { get; set; }
}
var t = new List<Tour>
{
new Tour
{
accountid = 1,
TourID = 2,
date = DateTime.Now,
purpose = "Testing"
}
};
var output = t.Where(c => c.accountid == accId).Select(k => new
{
accountid = k.accountid,
TourID = k.TourID,
TourDetails = k.date.ToString() + k.purpose
}).ToList();
var o = JsonConvert.SerializeObject(output);
You can use something like this if you're in a MVC Controller requiring an ActionResult as output :
//here 'context' is your DbContext implementation and Tours is your DbSet.
var TourDetails= context.Tours.Where(t=>t.AccountID==_AccID)
.Select(s=>new {
AccountID = s.accountid,
TourID = s.TourID,
//s.fromdate.ToString("yyyyMMddHHmmss") use this to format your date if needed
TourDetails = s.fromdate.ToString() + s.purpose
})
.ToList();
//JsonRequestBehavior.AllowGet only if your not using POST method
return Json(TourDetails, JsonRequestBehavior.AllowGet);

Select multiple columns in LINQ

I've written a LINQ query shown below :
List<Actions> actions = resourceActions.Actions.Select(s => s.ActionName).ToList();
How do I give for selecting multiple columns here ? ie I want to add columns s.ActionId and s.IsActive. I'm unable to apply it.
Make a class to represent the data you want:
public class ResourceAction
{
public int Id {get;set;}
public string Name {get; set; }
}
Select a list of those instead:
List<ResourceAction> actions = resourceActions.Actions
.Select(s => new ResourceAction() { Id = s.Id, Name = s.ActionName}).ToList();
I believe this is what your looking for. However you need to change the output to an anonymous type.
var actions = resourceActions.Actions.Select(s => new { s.ActionName, s.ActionId, s.IsActive } ).ToList();
You can use a anonymous type for this, for example
var actions = resourceActions.Actions.Select(s =>
new { Id = s.Id, Name = s.ActionName, Active = s.IsActive).ToList();
but a better way would be to create a class like
public class ActionWithId
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
}
List<ActionWithId> actions = resourceActions.Actions.Select(s =>
new ActionWithId() { Id = s.Id, Name = s.ActionName, Active = s.IsActive }).ToList();

LINQ GroupBy month

I am having trouble getting an IQueryable list of a (subsonic) object grouped by Month and Year.
Basic view of the object...
public partial class DatabaseObject
{
[SubSonicPrimaryKey]
public int objectID { get; set; }
public string Description { get; set; }
public decimal Value { get; set; }
public string Category { get; set; }
public DateTime DateOccurred { get; set; }
}
Method to get IQueryable in my Database repository...
public IQueryable GetData(string DataType)
{
return (from t in db.All<DatabaseObject>()
orderby t.DateOccurred descending
select t)
.Where(e => e.Category == DataType);
}
My question is, how can I return the dates grouped by Month? I have tried the below, but this results in compiler warnings regarding anonymous types...
public IQueryable GetData(string DataType)
{
var datalist = (from t in db.All<FinancialTransaction>().Where(e => e.Category == DataType);
let m = new
{
month = t.DateOccurred.Month,
year = t.DateOccurred.Year
}
group t by m into l select new
{
Description = string.Format("{0}/{1}", l.Key.month, l.Key.year),
Value = l.Sum(v => v.Value), // Sum(v => v.Value),
Category = "Grouped"
DateOccurred = l.Last(v => v.DateOccurred)
}
return datalist;
}
Any ideas?
Try this couple issues i found, but you basically need to select a Database object versus anonymous type?
IQueryable<DatabaseObject> datalist = (
from t in db.All<FinancialTransaction>().Where(e => e.Category == DataType)
let m = new
{
month = t.DateOccurred.Month,
year = t.DateOccurred.Year
}
group t by m into l
select new DatabaseObject()
{
Description = string.Format("{0}/{1}", l.Key.month, l.Key.year),
Value = l.Sum(v => v.Value), //Sum(v => v.Value),
Category = "Grouped",
DateOccurred = l.Max(v => v.DateOccurred)
}).AsQueryable();
Let me know if my solution is now what you want. I also noticed you were using Last? The extension you were using I do not have so I replaced it with Max. I don't have subsonic installed so it might come with the libraries.
Any way don't combine LINQ in query syntax and LINQ in extension methods syntax. Use next:
from t in db.All<DatabaseObject>()
where e.Category equals DataType
orderby t.DateOccurred descending
select t;
The issue is apparantly to do with the way Subsonic interprests certain linq statements and is a known bug.
IEnumerable<DatabaseObject> datalist = (
from t in db.All<FinancialTransaction>().Where(e => e.Category == DataType).ToList()
let m = new
{
month = t.DateOccurred.Month,
year = t.DateOccurred.Year
}
group t by m into l
select new DatabaseObject()
{
Description = string.Format("{0}/{1}", l.Key.month, l.Key.year),
Value = l.Sum(v => v.Value), //Sum(v => v.Value),
Category = "Grouped",
DateOccurred = l.Max(v => v.DateOccurred)
}).AsQueryable();
I have fixed this by declaring an list of type IEnumerable and using ToList() to cast the database interaction, finally the query is then recast AsQueryable()

Resources