I have some troubles with Loading Related Entities with a method group in EF.
In simple queries the Loading of Related Entities works ok with Include.
For example:
var result =
Repository.Query<TimeState>(x => x.Accepted == 0 && x.ProjectID != null && myTeam.Contains(x.EmployeeID))
.Include(typeof(Project).Name)
.Include(typeof(Employee).Name)
.Include(typeof(EmployeeDetails).Name)
.OrderByDescending(x => x.SubmitedDate);
Works perfect, and Loads the Project and the Employee
but in the next query does not load the Project and the Employee
var result2 = from item in Repository.Query<TimeState>(x => x.Accepted == 0 && x.ProjectID != null)
.Include(typeof(Project).Name)
.Include(typeof(Employee).Name)
.Include(typeof(EmployeeDetails).Name)
let projectId = (int)item.ProjectID
let isA = projectsIds.Contains(projectId) && item.Employee.EmployeeDetails.SuperiorID == id
let isB = item.Project.ManagerID == id && employeesTeam.Contains(item.EmployeeID)
where isA || isB
orderby item.SubmitedDate descending
select item;
I tried to do such a change: select new { item, item.Employee, item.Project };
var result3 = from item in Repository.Query<TimeState>(x => x.Accepted == 0 && x.ProjectID != null)
.Include(typeof(Project).Name)
.Include(typeof(Employee).Name)
.Include(typeof(EmployeeDetails).Name)
let projectId = (int)item.ProjectID
let isA = projectsIds.Contains(projectId) && item.Employee.EmployeeDetails.SuperiorID == id
let isB = item.Project.ManagerID == id && employeesTeam.Contains(item.EmployeeID)
where isA || isB
orderby item.SubmitedDate descending
select new { item, item.Employee, item.Project };
After that, result3[0].Employee has a value, the same for result3[0].Project (or any other item from that collection).
The problem is that I don't need the Employee and the Project as separate properties in this dynamic object result3.
How is possible to have Employee and Project in the method which returns result2 ? :)
I rarely use query syntax, and I've never run into someone using .Include(typeof(..).Name) syntax so try the following:
var result2 = (from item in Repository.Query<TimeState>(x => x.Accepted == 0 && x.ProjectID != null)
let projectId = (int)item.ProjectID
let isA = projectsIds.Contains(projectId) && item.Employee.EmployeeDetails.SuperiorID == id
let isB = item.Project.ManagerID == id && employeesTeam.Contains(item.EmployeeID)
where isA || isB
orderby item.SubmitedDate descending
select item)
.Include(i=>i.Projects)
.Include(i=>i.Employees)
.Include(i=>i.EmployeeDetails);
You may need to include using System.Data.Entity; as well for this to work.
Related
When I run the Linq query on LinqPad it takes only 4-5 seconds to return 5000 rows but when I run that same query in my code using Entity Framework it throws timeout.
What could be the possible issues?
Thanks in advance.
Below is the query:
var resultSale =
from product in Products
join productInfo in ProductInfoSummaries on product.ID equals productInfo.ProductID
join productDetail in ProductDetails on new { Id = product.ID, storeId = product.CreatedInStore } equals new { Id = productDetail.ProductID, storeId = productDetail.StoreID }
join productInventoryOtherStore in InventoryOtherStores on product.ID equals productInventoryOtherStore.ProductID
into productInventories
from productInventoryOtherStore in productInventories.DefaultIfEmpty()
join saleLine in SaleLines on productDetail.ID equals saleLine.ArtikkelNr
join sales in Sales on saleLine.OrderID equals sales.ID
where saleLine.ArtikkelNr != null
&& saleLine.DatoTid >= new DateTime(2018, 01, 01)
&& saleLine.DatoTid <= new DateTime(2019,11,21)
&& sales.StoreID == 14
&& (sales.OrderType == 1 || sales.OrderType == 2 || sales.OrderType == 4 || sales.OrderType == 6)
&& productDetail.SupplierProductNo != null
&& productDetail.Deleted == null
&& (productInfo.Inactive == null || productInfo.Inactive == false)
&& (product.CreatedInStore == 14 || product.CreatedInStore == 0 || product.CreatedInStore == null)
group new { saleLine.AntallEnheter, sales.OrderType } by new { product.ID, productInventoryOtherStore.Amount } into g
select new ProductSaleSummaryVM
{
ID = g.Key.ID,
Inventory = (double)g.Key.Amount,
TotalSold = g.Sum(x => x.OrderType !=4 ? x.AntallEnheter : 0) ?? 0,
TotalWastage = g.Sum(x => x.OrderType ==4 ? x.AntallEnheter : 0) ?? 0,
TotalOrderedQty = 0
};
var resultSupplierOrder =
from supplierOrderLine in SupplierOrderLines
join supplierOrder in SupplierOrders on supplierOrderLine.SupplierOrderID equals supplierOrder.ID
where supplierOrderLine.Deleted == null
&& supplierOrder.Status != 1
&& supplierOrder.StoreID == 14
group supplierOrderLine by supplierOrderLine.ProductID into g
select new ProductOrderDetailsVM
{
ID = g.Key,
TotalOrderedQty = (double)g.Sum(x => x.ConsumerQuantity - x.QuantiyReceived)
};
var r =
(from resSale in resultSale
join resSupplierOrder in resultSupplierOrder on resSale.ID equals resSupplierOrder.ID
into resSupplierOrders
from resSupplierOrder in resSupplierOrders.DefaultIfEmpty()
orderby resSale.ID
select new ProductSaleSummaryVM
{
ID = resSale.ID,
Inventory = resSale.Inventory,
TotalSold = resSale.TotalSold,
TotalWastage = resSale.TotalWastage,
TotalOrderedQty = resSupplierOrder.TotalOrderedQty ?? 0
})
.Where(x => x.Inventory + x.TotalOrderedQty < x.TotalSold);
r.Dump();
Try using entity framework within linqpad see if it gives you any clues. see this link on how to use entity framework in linqpad
https://www.linqpad.net/EntityFramework.aspx
This behaviour could be related to parameter sniffing - check this article for details
i don't know how to handle this in LINQ
simply i have a searchKey in which i am passing user enter data and it return with rows. but if i am not passing any searchkey it not given any data. i dont want to add contains if searchkey is empty :(
var AppointmentList = (from app in Con.ios_Appointment
where (app.IS_DELETED == false && app.CLINICIANID == appReq.id
&& app.FNAME.Contains(appReq.searchKey.Trim()) || app.LNAME.Contains(appReq.searchKey.Trim()) || app.ADDRESS.Contains(appReq.searchKey.Trim())
)
orderby app.DATE descending
select new
{
app.ID,
app.FNAME,
app.LNAME,
app.DATE,
app.LONGITUDE,
app.LATITUDE,
app.ADDRESS,
app.STATUS,
app.START_TIME
}).Skip(skipRecord).Take(Convert.ToInt32(record)).ToList();
I suggest you use method syntax to easily build the query up programatically:
var query = Con.ios_Appointment.Where(app => !app.IS_DELETED && app.CLINICIANID == appReq.id);
var search = appReq.searchKey.Trim();
if (search != "")
{
query = query.Where(app => app.FNAME.Contains(search) ||
app.LNAME.Contains(search) ||
app.ADDRESS.Contains(search));
}
var appointments = query
.OrderByDescending(app => app.DATE)
.Select(app => new
{
app.ID,
app.FNAME,
app.LNAME,
app.DATE,
app.LONGITUDE,
app.LATITUDE,
app.ADDRESS,
app.STATUS,
app.START_TIME
})
.Skip(skipRecord)
.Take(Convert.ToInt32(record))
.ToList();
You need to use string.IsNullOrWhiteSpace method:
where (app.IS_DELETED == false &&
app.CLINICIANID == appReq.id &&
(string.IsNullOrWhiteSpace(appReq.searchKey) ||
app.FNAME.Contains(appReq.searchKey.is Trim()) || ...
This is my Code where I am fetching data.
var list = (from u in _dbContext.Users
where u.IsActive
&& u.IsVisible
&& u.IsPuller.HasValue
&& u.IsPuller.Value
select new PartsPullerUsers
{
AvatarCroppedAbsolutePath = u.AvatarCroppedAbsolutePath,
Bio = u.Bio,
CreateDateTime = u.CreationDate,
Id = u.Id,
ModifieDateTime = u.LastModificationDate,
ReviewCount = u.ReviewsReceived.Count(review => review.IsActive && review.IsVisible),
UserName = u.UserName,
Locations = (from ul in _dbContext.UserLocationRelationships
join l in _dbContext.Locations on ul.LocationId equals l.Id
where ul.IsActive && ul.UserId == u.Id
select new PartsPullerLocation
{
LocationId = ul.LocationId,
Name = ul.Location.Name
}),
Rating = u.GetPullerRating()
});
Now Here is my Extension.
public static int GetPullerRating(this User source)
{
var reviewCount = source.ReviewsReceived.Count(r => r.IsActive && r.IsVisible);
if (reviewCount == 0)
return 0;
var totalSum = source.ReviewsReceived.Where(r => r.IsActive && r.IsVisible).Sum(r => r.Rating);
var averageRating = totalSum / reviewCount;
return averageRating;
}
I have check this Post LINQ to Entities does not recognize the method
And I come to know I need to use
public System.Linq.Expressions.Expression<Func<Row52.Data.Entities.User, int>> GetPullerRatingtest
But how ?
Thanks
You can use conditionals inside LINQ to Entity queries:
AverageRating = u.ReviewsReceived.Count(r => r.IsActive && r.IsVisible) > 0 ?
u.ReviewsReceived.Where(r => r.IsActive && r.IsVisible).Sum(r => r.Rating) /
u.ReviewsReceived.Count(r => r.IsActive && r.IsVisible)
: 0
This will be calculated by the server, and returned as part of your list. Although with 10 million rows like you said, I would do some serious filtering before executing this.
Code within LINQ (to Entities) query is executed within database, so you can't put random C# code there. So you should either use user.GetPullerRating() after it is retrieved or create a property if you don't want to do the calculation every time.
You can also do:
foreach (var u in list)
u.Rating = u.GetPullerRating()
By the way, why is it extension method.
I have Table HR_Travel(TravelID, TravelCode....) and HR_TravelDocuments(TravelDocID, TravelID, DocUrl)
FromDate = FromDate.AddDays(1);
ToDate = ToDate.AddDays(1);
List<dynamic> Lst = new List<dynamic>();
var queryTravelDetails = from t in db.HR_TravelDetails
where ((t.StatusDate >= FromDate && t.StatusDate <= ToDate)
&& (t.EmpID == EmpID || EmpID == 0) && (t.TravelStatus == TravelStatus || TravelStatus == "All"))
orderby t.StatusDate descending
select new
{
TravelID = t.TravelID,
TravelSubID = db.HR_TravelDetails.Where(i => i.TravelID == 0).FirstOrDefault().TravelID == null ? 0 : db.HR_TravelDetails.Where(i => i.TravelID == 0).FirstOrDefault().TravelID,
t.TravelCode,
t.EmpID,
EmpName = db.EE_Employee.Where(i => i.EmpID == t.EmpID).FirstOrDefault().EmpName,
t.CellNo,
t.BoardingForm,
t.DestinationTO,
t.JournyDate,
t.Purpose,
t.Organization,
t.TravelStatus,
DocUrl = DocUrl = string.Join(",",( db.HR_TravelDocuments.Where(i => i.TravelID == t.TravelID && i.TravelSubID == 0).Select(i => i.DocUrl).ToList()))
};
foreach (var element in queryTravelDetails)
{
Lst.Add(element);
}
Gives the following error:
LINQ to Entities does not recognize the method 'System.String Join[String](System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.
The Join() method can't be used in LINQ expressions, because it cannot translate from CLR to T-SQL. Another example is that you can't use:
var itemCount = db.Table.Count(p => p.Something == SomeFunction(someVariable));
You should move the method call outside the LINQ statement:
var anotherVariable = SomeFunction(someVariable);
var itemCount = db.Table.Count(p => p.Something == anotherVariable);
I hope I explained in a good way.
EDIT: As seen in the comments before, you can also use ToArray() and when the data is loaded locally you can use functions in statements freely.
I am trying to take the SQL code below and turn turn it into an EF select statement. I pretty much have it finished except I am stuck on how to do a NOT IN in entity framerwork.
MS SQL SELECT
SELECT * from friends as f
WHERE (f.id NOT IN (Select friendid from users_friends where userid = 1))
AND (f.lastname LIKE '%b%' OR f.firstname LIKE '%b%' OR f.alias LIKE '%b%')
My EF select without the NOT IN part
var friends =
(from f in db.Friends
select new FriendModel()
{
Id = f.Id,
Alias = f.Alias,
CarrierId = f.CarrierId,
CreatedOn = f.CreatedOn,
FirstName = f.FirstName,
LastName = f.LastName,
Locked = f.Locked,
PhoneNumber = f.PhoneNumber,
SteamId = f.SteamId,
Carrier = new CarrierModel()
{
CarrierName = f.Carrier.CarrierName,
CarrierEmail = f.Carrier.CarrierEmail
}
}).Where(
f => (f.Alias.Contains(query) || f.FirstName.Contains(query) || f.LastName.Contains(query)))
.OrderBy(f => f.Alias)
.ToList();
I guess this is what you want:
var friendIds = db.users_friends.Where(f => f.userid == 1).Select(f => f.friendid);
var friends = db.Friends.Where(f => !friendIds.Contains(f.Id) &&
(f.Alias.Contains(query) ||
f.FirstName.Contains(query) ||
f.LastName.Contains(query)))
.Select(f => new FriendModel() { ... })
.OrderBy(f => f.Alias)
.ToList();
Assuming User entity has a collection of Friend entity.
.Where(f => (f.Alias.Contains(query) || f.FirstName.Contains(query) || f.LastName.Contains(query))
&& !context.Users.FirstOrDefault(u=>u.UserId == 1)
.Friends.Any(uf=>uf.FriendId == f.FriendId))
If not, query the UserFriend table directly
.Where(f => (f.Alias.Contains(query) || f.FirstName.Contains(query) || f.LastName.Contains(query))
&& !context.UserFriends.Any(uf=>uf.UserId == 1 && uf.FriendId == f.FriendId)