Subsonic 3.0 UPDATE, multiple conditions - sql-server

db.Update<Luna.Record.TB_ITEM>().Set(
x => x.ITEM_DURABILITY == Convert.ToInt32(quantity))
.Where(x => x.ITEM_POSITION == Convert.ToInt32(position))
.Execute();
How will I add an AND clause this is how it looks like in plain SQL:
UPDATE TB_ITEM
SET ITEM_DURABITLITY=#quantity
WHERE ITEM_POSITION=#position AND CHARACTER_IDX=#charidx

.Where(x => x.ITEM_POSITION == Convert.ToInt32(position)
&& x.CHARACTER_IDX == Convert.ToInt32(charidx))

Related

LINQ Additional Filter in Select Statement

I am unfamiliar with LINQ and I am trying to modify an existing query.
Below is the code snippet and the filter that I would like to add in:
ViewData["Employees"] = emps = (from staff in db.Staffs
from jobinfo in db.JobInfo
.Where(x => x.staff_id == staff.StaffID)
.OrderByDescending(x => x.jobinfo_id).Take(1)
select new { staff, jobinfo })
.Select(x => x.staff).Distinct().OrderBy(x => x.Alias).ToList();
*** Insert Additional filter at the .Select statement above
<where (jobinfo.last_date == null)>
May I know how can it be done?
Could you please try like below and check in the third line?
.Where(x => x.staff_id == staff.StaffID && x.last_date == null)
two options one is to use && and use another where as follows
ViewData["Employees"] = emps = (from staff in db.Staffs
from jobinfo in db.JobInfo
.Where((x => x.staff_id == staff.StaffID) && (jobinfo.last_date == null))
.OrderByDescending(x => x.jobinfo_id).Take(1)
select new { staff, jobinfo })
.Select(x => x.staff).Distinct().OrderBy(x => x.Alias).ToList();
Other options would be
ViewData["Employees"] = emps = (from staff in db.Staffs
from jobinfo in db.JobInfo
.Where((x => x.staff_id == staff.StaffID)).Where(jobinfo.last_date == null)
.OrderByDescending(x => x.jobinfo_id).Take(1)
select new { staff, jobinfo })
.Select(x => x.staff).Distinct().OrderBy(x => x.Alias).ToList();

Insert Additional Condition in LINQ

I am modifying a LINQ query in SQL Server 2014, but I have never used the syntax:
if (!UserAccessMatrixSession.HasRole(Session, Constant.ROLE_STAFF))
{
if (country != 0 )
{
ViewData["Employees"] = (from staff in db.Staffs
from jobinfo in db.JobInfo
.Where(x => x.staff_id == staff.StaffID)
.OrderByDescending(x => x.jobinfo_id).Take(1)
orderby staff.Alias
select new { staff, jobinfo }).Where(x => x.jobinfo.location == country)
.Select(x => x.staff).ToList();
}
else
{
ViewData["Employees"] = (from staff in db.Staffs
orderby staff.Alias
select staff).ToList();
}
}
I would like to insert an additional condition as follows:
where jobinfo.last_date == null OR DateTime.Now < jobinfo.last_date
I believe you would want to add that where clause into where you are selecting from the job info
if (!UserAccessMatrixSession.HasRole(Session, Constant.ROLE_STAFF))
{
if (country != 0 )
{
ViewData["Employees"] = (from staff in db.Staffs
from jobinfo in db.JobInfo
.Where(x => x.staff_id == staff.StaffID)
.OrderByDescending(x => x.jobinfo_id).Take(1)
orderby staff.Alias
select new { staff, jobinfo }).Where(x => x.jobinfo.location == country
/* last_date null or UtcNow < last_date*/ && (x.jobinfo.last_date == null || DateTime.UtcNow < jobinfo.last_date))
.Select(x => x.staff).ToList();
}
else
{
ViewData["Employees"] = (from staff in db.Staffs
orderby staff.Alias
select staff).ToList();
}
}

Query doesn't run when using Context supplied by Unity IoC

Behold incredible wiredness....
Here's my query....
var searchParams = new SearchParameters {FirstName = "Ian"};
var query =
Context.Prospects
.Where(p =>
p.ProspectId == searchParams.ProspectId
|| p.Contact.FirstName.ToLower().Contains(searchParams.FirstName.ToLower())
|| p.Contact.LastName.ToLower().Contains(searchParams.LastName.ToLower())
|| p.Contact.PhoneNumber.Contains(searchParams.PhoneNumber))
.Join(Context.ProspectEvents, p => p.ProspectId, pe => pe.ProspectId,
(p, pe) => new {Prospect = p, ProspectEvent = pe})
.Join(Context.Lookup_Event, p => p.ProspectEvent.EventId, e => e.EventId,
(p, e) => new {p.Prospect, p.ProspectEvent, Event = e})
.Where(
x =>
x.ProspectEvent.Date ==
Context.ProspectEvents.Where(pe => pe.ProspectId == x.Prospect.ProspectId)
.Max(pe => pe.Date)
).ToList();
This query is running against SQL Server 2000. I'm not sure how this could make a difference but I didn't have a problem running against 2012.
The last 'where' clause doesn't run when the EF context is provided by Unity IoC!
The error is...
Only primitive types or enumeration types are supported in this
If I 'new' up a context just before the query then it works.
Any ideas??

Sum of multiple queries to optimise number of queries performed

I have a query which must sum the values from several tables and add the result. The system is simply an inventory system and I'm trying to get the stock level by calculating incomings (deliveries), outgoings (issues) and adjustments to items.
As the stock level is a calculated value (sum(deliveries) - sum(issues)) + sum(adjustments) I am trying to create a function that will get this value with a minimal number of queries.
At current I have linq that performs three separate queries to get each summed value and then perform the addition/subtraction in my function, however I am convinced there must be a better way to calculate the value without having to do three separate queries.
The current function is as follows:
public static int GetStockLevel(int itemId)
{
using (var db = EntityModel.Create())
{
var issueItemStock = db.IssueItems.Where(x => x.ItemId == itemId).Sum(x => x.QuantityFulfilled);
var deliveryItemStock = db.DeliveryItems.Where(x => x.ItemId == itemId).Sum(x => x.Quantity);
var adjustmentsStock = db.Adjustments.Where(x => x.ItemId == itemId).Sum(x => x.Quantity);
return (deliveryItemStock - issueItemStock) + adjustmentsStock;
}
}
In my mind the SQL query is quite simple, so I have considered a stored procedure, however I think there must be a way to do this with linq.
Many thanks
Edit: Answer
Taking the code from Ocelot20's answer, with a slight change. Each of the lets can return a null, and if it does then linq throws an exception. Using the DefaultIfEmpty command will negate this, and return a 0 for the final calculation. The actual code I have used is as follows:
from ii in db.Items
let issueItems = db.IssueItems.Where(x => x.ItemId == itemId).Select(t => t.QuantityFulfilled).DefaultIfEmpty(0).Sum()
let deliveryItemStock = db.DeliveryItems.Where(x => x.ItemId == itemId).Select(t => t.Quantity).DefaultIfEmpty(0).Sum()
let adjustmentsStock = db.Adjustments.Where(x => x.ItemId == itemId).Select(t => t.Quantity).DefaultIfEmpty(0).Sum()
select (deliveryItemStock - issueItems) + adjustmentsStock);
Without knowing what your entities look like, you could do something like this:
public static int GetStockLevel(int itemId)
{
using (var db = EntityModel.Create())
{
// Note: Won't work if there are no IssueItems found.
return (from ii in db.IssueItems
let issueItems = db.IssueItems.Where(x => x.ItemId == itemId)
.Sum(x => x.QuantityFulfilled)
let deliveryItemStock = db.DeliveryItems.Where(x => x.ItemId == itemId)
.Sum(x => x.Quantity)
let adjustmentsStock = db.Adjustments.Where(x => x.ItemId == itemId)
.Sum(x => x.Quantity)
select issueItems + deliveryItemStock + adjustmentsStock).FirstOrDefault() ?? 0;
}
}
I tested a similar query on my own db and it worked in a single query. I suspect that since they all have a common ItemId, that using entity relations could make this look something like:
// Ideal solution:
(from i in db.Items
where i.Id == itemId
let issueItems = i.IssueItems.Sum(x => x.QuantityFulfilled)
let deliveryItemStock = i.DeliveryItems.Sum(x => x.Quantity)
let adjustmentsStock = i.Adjustments.Sum(x => x.Quantity)
select issueItems + deliveryItemStock + adjustmentsStock).SingleOrDefault() ?? 0;
Have you considered adding a view to the database that performs the calculations that you can then just use a simple select query (or SP) to return the values that you need?
I reckon this should work and the SQL generated is not particularly complex. If you think there is something wrong with it let me know and I will update my answer.
public static int GetStockLevel(int itemId)
{
using (var db = EntityModel.Create())
{
return db.IssueItems.Where(x => x.ItemId == itemId).GroupBy(x => x.ItemId)
.GroupJoin(db.DeliveryItems, x => x.First().ItemId, y => y.ItemId, (x, y) => new
{ Issues = x, Deliveries = y})
.GroupJoin(db.Adjustments, x=> x.Issues.First().ItemId, y=> y.ItemId, (x, y) => new
{
IssuesSum = x.Issues.Sum(i => i.QuantityFullfilled),
DeliveriesSum = x.Deliveries.Sum(d => d.Quantity),
AdjustmentsSum = y.Sum(a => a.Quantity)})
.Select(x => x.IssuesSum - x.DeliverysSum + x.AdjustmentsSum);
}
}

How to Convert sql server query to linq in entity framework

I am converting the sql server query to linq
SELECT * FROM DataFlow where FlowDeleted = 0 and
DataFlow.FlowVersionNumber =
(
SELECT MAX(FlowVersionNumber) from DataFlow i
where FlowDeleted = 0 AND
i.FlowCounter = DataFlow.FlowCounter
group by FlowCounter
)
ORDER by 1
My Linq query Code is:
public List<DataFlow> getdataflow()
var dflow = db.DataFlows.Where (
d => d.FlowDeleted == false &&
d.FlowVersionNumber =
(
db.DataFlows.Where(i => i.FlowDeleted == false && i.FlowCounter == d.FlowCounter).GroupBy(g => g.FlowCounter)
.Select(s => s.Max(m => m.FlowVersionNumber))
)
)
.Select(s =>
new DataFlow
{
FlowCounter = s.FlowCounter,
FlowDescription = s.FlowDescription,
FlowName = s.FlowName,
}).OrderBy(o => o.FlowCounter);
return dflow.ToList();
}
But it giving error like: Operator '&&' cannot be applied to operands of type 'bool' ... 'string'"
Please help me
You are using assignment operator instead of comparing... try ..d.FlowVersionNumber ==...
db.DataFlows.Where(d =>
d.FlowDeleted == false &&
d.FlowVersionNumber == db.DataFlows.Where(i =>
i.FlowDeleted == false &&
i.FlowCounter == d.FlowCounter).GroupBy(g => g.FlowCounter)
.First(s => s.Max(m => m.FlowVersionNumber))
)
)
I changed Select to First because you need to compare scalars. However, be sure that you WILL find an item, or you could get an exception.

Resources