I want to implement the following SQL statement using entity framework:
select coalesce(SUM(cdin_ActMortgageAmnt), 0)
from CRM.dbo.CDIndex,CRM.dbo.company
where comp_companyid = cdin_companyid
and comp_idcust like '%10319%'
and cdin_Deleted is null
and cdin_startunstufdate is not null
and cdin_Status = 'InProgress'
I tried to get the sum of cdin_ActMortgageAmnt:
Company c = db.Companies.Find(750);
var CGP = (from cd in db.CDIndexes
join com in db.Companies on cd.cdin_CompanyId equals com.Comp_CompanyId
where com.Comp_IdCust == c.Comp_IdCust &&
cd.cdin_Deleted == null &&
cd.cdin_startunstufdate == null &&
cd.cdin_Status == "InProgress"
select new
{
act = cd.cdin_ActMortgageAmnt == null ? 0 : cd.cdin_ActMortgageAmnt
}
);
var query = CGP.Sum(x => x.act);
lblSum.Text = query.ToString();
But the query returns null while tracing...
Related
I need to get one value of the q2.RoomId in this linq query as below and pass it to string variable . and is it possible to set alias column name for select ?
var result = from q1 in _db.DormApplications
join q2 in _db.DormRooms
on q1.DormRoomId equals q2.Id
where q1.Poster == username && q1.Review == EnableType.YES
&& now > q1.Sdate && now <q1.Edate
select new { q1.Name, q1.Sdate, q1.Edate, q1.DormRoomId,
q2.RoomId };
I tried this to get q2.RoomId ,
String room = result[4].ToString();
but still cannot work ,please anyone can help me ?
If you know the query will only return one row you can write:
var result = (from q1 in _db.DormApplications
join q2 in _db.DormRooms
on q1.DormRoomId equals q2.Id
where
q1.Poster == username && q1.Review == EnableType.YES
&& now > q1.Sdate && now <q1.Edate
select
new {
q1.Name,
q1.Sdate,
q1.Edate,
q1.DormRoomId,
q2.RoomId
}).FirstOrDefault();
var roomId = result.RoomId;
var Name = result.Name;
I've tried to find a similar question but I haven't found exactly what I want.
I have this issue: about the following code I am not able to find a way to manage that if devTab is null then his property ID is not available and the where condition t.IDDevTab ==devTab.ID leads to null reference error. Mind that t.IDDevTab is not nullable in the DB. I have tried to insert some additional conditions to the Where but it resulted in error: invoke non static method requires a target. I would obtain a empty list in "DeviceTabColumnsNameAndDesc" if "devTab" is null!
DeviceTable devTab = (from t in _db.DeviceTables
where t.DeviceType == devtype && t.IDPlant == id
select t)
.FirstOrDefault();
var DeviceTabColumnsNameAndDesc = (from t in _db.DeviceTabCols
where t.IDDevTab == devTab.ID
&& t.MeasureFamily != "KEY"
&& t.MeasureFamily != "DATETIME"
select new
{
colName = t.ColumnName,
colDescr = t.ColumnDescr
})
.ToList();
Is there a workaround of this problem? Thank you in advance.
So, if devTab is null you want a new empty list of anonymous type.. Awkward, but doable:
DeviceTable devTab = (from t in _db.DeviceTables
where t.DeviceType == devtype && t.IDPlant == id
select t)
.FirstOrDefault();
var DeviceTabColumnsNameAndDesc = devTab == null ?
Enumerable.Empty<object>().Select(x => new { colName = "", colDescr = "" }).ToList() :
(
from t in _db.DeviceTabCols
where t.IDDevTab == devTab.ID && t.MeasureFamily != "KEY" && t.MeasureFamily != "DATETIME"
select new {
colName = t.ColumnName,
colDescr = t.ColumnDescr
}
).ToList();
If you wanted to switch away from anonymous types in this case, you could look at ValueTuple:
var DeviceTabColumnsNameAndDesc = devTab == null ?
new List<(string colName, string colDesc)>() :
(
from t in _db.DeviceTabCols
where t.IDDevTab == devTab.ID && t.MeasureFamily != "KEY" && t.MeasureFamily != "DATETIME"
select (
colName: t.ColumnName,
colDescr: t.ColumnDescr
)
).ToList();
Or make a record, which is like a class but with some extra bits that make it useful as a data holder:
//defined in a namespace
public record ColThing(string ColName, string ColDesc);
var DeviceTabColumnsNameAndDesc = devTab == null ?
new List<ColThing>() :
(
from t in _db.DeviceTabCols
where t.IDDevTab == devTab.ID && t.MeasureFamily != "KEY" && t.MeasureFamily != "DATETIME"
select new ColThing(t.ColumnName, t.ColumnDescr)
).ToList();
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 have a Linq to SQL query that behaves (in my opinion) very strange when I check for null values.
There is a record in the DB as shown by the last Linq, but why does the 1st two queries not show the record?
//Check
(record.SomeID == null ? "Yes" : "No"); //This prints Yes
//LINQ
var q = (from t in mySQLTable
where t.PKID == record.PKID &&
t.SomeID == record.SomeID
select t).FirstOrDefault();
//This prints nothing. I.e. no records found
var q2 = (from t in mySQLTable
where t.PKID == record.PKID &&
t.SomeID == (record.SomeID == null ? null : record.SomeID)
select t).FirstOrDefault();
//This also prints nothing. I.e. no records found
var q3 = (from t in mySQLTable
where t.PKID == record.PKID &&
t.SomeID == null
select t).FirstOrDefault();
//This prints 1 record
You can overcome this issue using the below query:
bool isNull = record.SomeID == null;
var q = (from t in mySQLTable
where t.PKID == record.PKID
&& ( (isNull && t.SomeID == null)
||
(!isNull && t.SomeID == record.SomeID)
)
select t).FirstOrDefault();
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.