I need to run this query in a oracle 11.2 database, but the generated query contains a "OUTER APPLY". How can I solve it ?
var query = from r in Ctx.Reg
let status_1 = (r.Hist.OrderByDescending(o => o.Id).FirstOrDefault(h => h.RegId == r.Id).Status == 1)
let status_2 = (r.Hist.OrderByDescending(o => o.Id).Skip(1).FirstOrDefault(h => h.RegId == r.Id).Status == 2)
select new
{
r.Id,
...
status_1,
status_2
};
OUTER APPLY is generated by your let statement expressions. You can avoid it by turning them into EXISTS translatable expressions using the equivalent Any based LINQ constructs:
var query = from r in Ctx.Reg
let status_1 = r.Hist.OrderByDescending(h => h.Id).Take(1).Any(h => h.Status == 1)
let status_2 = r.Hist.OrderByDescending(h => h.Id).Skip(1).Take(1).Any(h => h.Status == 2)
select new
{
r.Id,
...
status_1,
status_2
};
Note that h.RegId == r.Id is not needed because that is implied by r.Hist navigation property.
Related
I have to fix a query which was already written in the LINQ Lambda, I found the fix in a Simple SQL Query but now I have some trouble in converting it to LINQ Query,
Here is my SQL Query
select * from RequestItem_SubRequestItem x
where x.RequestItem_key = 1 and x.SubRequestItem_key in (
select o.SubRequestItem_key
from SubRequestItem_Entitlement o
inner join SubRequestItem sr on sr.SubRequestItem_key = o.SubRequestItem_key
where o.Entitlement_key = 2 and sr.Action = 'Add' )
And below is my LINQ C# code where I am trying to insert my fixes which include inner join.
z.Entitlements = ARMContext.Context.SubRequestItem_Entitlement
.Where(o => o.Entitlement_key == z.AccessKey && !o.Role_key.HasValue && o.Entitlement.EntitlementConfiguration.UserVisible == true
&& (ARMContext.Context.RequestItem_SubRequestItem
.Where(x => x.RequestItem_key == requestItemKey)
.Select(y => y.SubRequestItem_key)
.Contains(o.SubRequestItem_key)))
.Join(ARMContext.Context.SubRequestItems, subrq => subrq.SubRequestItem_key, temp => requestItemKey, (subrq, temp) => subrq == temp)
Where as previously the C# LINQ code looked like this
z.Entitlements = ARMContext.Context.SubRequestItem_Entitlement
.Where(o => o.Entitlement_key == z.AccessKey && !o.Role_key.HasValue && o.Entitlement.EntitlementConfiguration.UserVisible == true
&& (ARMContext.Context.RequestItem_SubRequestItem
.Where(x => x.RequestItem_key == requestItemKey)
.Select(y => y.SubRequestItem_key)
.Contains(o.SubRequestItem_key)))
When I try to insert the JOIN in the LINQ as per my conditions then I get to see this error.
What is my mistake? Can anybody tell me a correct way to do it?
I think this should Suffice your need, although you might have to make changes to the other code which are dependent on your SubRequestItem_Entitlement table with {user, add}
please have a look at that. As I am sure you will have to make those changes.
.Join(ARMContext.Context.SubRequestItems, user => user.SubRequestItem_key, subreqItems => subreqItems.SubRequestItem_key, (user, subreqItems) => new { user, subreqItems })
.Where(Action => Action.subreqItems.Action == z.ApprovalAction)
you can use this query. I exactly matched the SQL query
var query = ARMContext.Context.RequestItem_SubRequestItem
.Where(a => a.RequestItem_key == 1 && a.RequestItem_key == (ARMContext.Context.SubRequestItem_Entitlement
.Join(ARMContext.Context.SubRequestItems,
right => right.SubRequestItem_key,
left => left.SubRequestItem_key,
(right, left) => new
{
right = right,
left = left
})
.Where(x => x.right.Entitlement_key == 2 && x.left.Action == "Add" && x.right.SubRequestItem_key == a.RequestItem_key).Select(y => y.right.SubRequestItem_key)).FirstOrDefault());
I am having difficulty converting this expression to SQL expression. I tried various applications but I failed. I tried to convert it myself but the result is different.
db.Trans_SAPStat.Where(s => s.EmployeeID == EmployeeID && s.PaymentID != PaymentID && !s.Status.Equals("cancelled or", StringComparison.OrdinalIgnoreCase))
.Join(_db.Trans_PaymentDetail,
stat => stat.PaymentID,
paydet => paydet.PaymentID,
(stat, paydet) => new
{
InvoiceNo = paydet.Remarks,
paydet.Amount,
stat.Status,
paydet.PaymentCode
})
.Where(s => s.PaymentCode.ToLower() == "c")
.GroupBy(g => g.InvoiceNo)
.Select(lg =>
new
{
InvoiceNo = lg.Key,
TotalAmount = lg.Sum(w => w.Amount)
}).ToList();
If you have this code inside working application then try to use SQL profiler. Another option - linqpad
Try this:
SELECT
p.Remarks AS InvoiceNo,SUM(p.Amount) AS TotalAmount
FROM Trans_SAPStat AS s
INNER JOIN Trans_PaymentDetail AS p ON s.PaymentID = p.PaymentID
WHERE s.EmployeeID = #EmployeeID
AND s.PaymentID <> #PaymentID
AND LOWER(s.Status) <> 'cancelled or'
AND LOWER(s.PaymentCode) = 'c'
GROUP BY p.Remarks
You can try to set the query to a variable without materialization (.ToList()), then just use query.ToString(). This will return the actual SQL query.
var query = db.Trans_SAPStat.Where(....); // don't call .ToList()
var sqlQuery = query.ToString();
var result = query.ToList(); // materialization
NOTE: This is the default behaviour for entity framework / linq to entities IQueryable<T> interface.
Is it possible to use If Else conditional in a LINQ query?
Something like
from p in db.products
if p.price>0
select new
{
Owner=from q in db.Users
select q.Name
}
else
select new
{
Owner = from r in db.ExternalUsers
select r.Name
}
This might work...
from p in db.products
select new
{
Owner = (p.price > 0 ?
from q in db.Users select q.Name :
from r in db.ExternalUsers select r.Name)
}
I assume from db that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects);
Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?).
For a trivial example of the type of thing you can do:
select new {p.PriceID, Type = p.Price > 0 ? "debit" : "credit" };
You can do much richer things, but I really doubt you can pick the table in the conditional. You're welcome to try, of course...
Answer above is not suitable for complicate Linq expression.
All you need is:
// set up the "main query"
var test = from p in _db.test select _db.test;
// if str1 is not null, add a where-condition
if(str1 != null)
{
test = test.Where(p => p.test == str);
}
var result = _context.Employees
.Where(x => !x.IsDeleted)
.Where(x => x.ClientId > (clientId > 0 ? clientId - 1 : -1))
.Where(x => x.ClientId < (clientId > 0 ? clientId + 1 : 1000))
.Where(x => x.ContractorFlag == employeeFlag);
return result;
If clientId = 0 we want ALL employees,. but for any clientId between 1 and 999 we want only clients with that ID. I was having issues with seperate LINQ statements not being the same (Deleted/Clients filters need to be on all queries), so by add these two lines it works (all be it until we have 999+ clients - which would be a happy re-factor day!!
you should change like this:
private string getValue(float price)
{
if(price >0)
return "debit";
return "credit";
}
//Get value like this
select new {p.PriceID, Type = getValue(p.Price)};
my example:
companyNamesFirst = this.model.CustomerDisplayList.Where(a => a.CompanyFirst != null ? a.CompanyFirst.StartsWith(typedChars.ToLower())) : false).Select(b => b.CompanyFirst).Distinct().ToList();
If you are using LinQ with EF Core, an easy example can be this-
var orderedData = await _dbContext.ModelName
.OrderBy(c => c.Name.Length.Length > 4 ? c.Name:c.SuperTerm.Name.IndexOf(searchValue))
.ThenBy(t => t.Producer)
.TolistAsync();
I am reasonably new to Linq and it seems quite easy to iuse but I am having an issue when trying to extract a value from a table that is linked/constrained by 3 other tables.
I have this in my SQL DB:
I am using Asp.Net 4 and Entity Framework 6.
I have as a parameter the 'DatabaseName'.
I ultimately want to get the SubscriptionRef that is assigned to this name.
I could do this step-by-step (ie using multiple linqs) but I thought it would look 'clean' using just 1 linq statment.
I have got as far as this:
var names = o.RegisteredNames.Where(d => d.DatabaseName == DBName).Where(d => d.ClientNames.Where(f => f.ClientId == f.Client.ClientId).FirstOrDefault();
But I get the error:
Cannot implicitly convert type 'Services.ClientName' to 'bool'
You have a Problem here:
d => d.ClientNames.Where(f => f.ClientId == f.Client.ClientId)
f => ... returns a single ClientName or null, which causes your error, because there should be a boolean.
If you want this first value or null, you should replace
.Where(d => d.ClientNames ...
//with
.Select(d => d.ClientNames ...
Try this:
o.RegisteredNames.First(d => d.DatabaseName == DBName).ClientNames.Select(x=>x.Client.Subscription.SubscriptionRef)
It should give you list go SubscriptionRef.
You can try with one LINQ query like...
var names = o.RegisteredNames.Where(d => d.DatabaseName == DBName ).FirstOrDefault();
You might wanna try sql style:
var client = from c in db.Clients
join cn in db.ClientNames on c.ClientId equals cn.ClientId
join rn in db.RegisteredNames on cn.RegisteredNamesId equals rn.RegisteredNameId
where rn.DatabaseName == "YourDBName"
select c;
But it also depends on how your objects were built.
Try using join:
var names = (
from names in o.RegisteredNames.Where(d => d.DatabaseName == DBName)
join cnames in o.ClientNames on names.RegisteredNamesId equals cnames.RegisteredNamesId
select cnames.ClientId
).FirstOrDefault();
Add as many joins as you want.
Try this
It works in List,
var option1= o.RegisteredNames
.Where(g => g.DbName == "YourDbName")
.Where(h => h.ClientNames.Any(f => f == 5))
.FirstOrDefault();
var option2= o.RegisteredNames
.FirstOrDefault(h => h.DbName == "Name" && h.ClientNames.Any(j => j == 1));
I want to do something like that;
Context.Users.Include("Addresses", a => a.IsRowDeleted == false).FirstOrDefault(u => u.UserId == 5);
I mean; I want to filter included entities but not always, its also have to be optional.
What is the best solution for this? Please help me,
You cannot filter eager loaded data in EF. Include operation doesn't support filtering or sorting.
You must use either projection to custom type (or anonymous type):
var query = from u in context.Users
where u.UserId == 5
select new UserFiltered
{
User = u,
Addresses = u.Addresses.Where(a => !a.IsRowDeleted)
};
UserFiltered u = query.FirstOrDefault();
Or you must devide your query into two separated queries and use explicit loading:
context.ContextOptions.LazyLoadingEnabled = false;
var user = context.Users.FirstOrDefault(u => u.UserId == 5);
((EntityCollection<Address>)user.Addresses)
.CreateSourceQuery()
.Where(a => !a.IsRowDeleted)
.Execute();
Or you can simply use two queries:
var user = context.Users.FirstOrDefault(u => u.UserId == 5);
var addresses = context.Addresses.Where(a => a.User.UserId == 5 && !a.IsRowDeleted).ToList();
Do you mean something like (warning: untested code):
Context.Users.SingleOrDefault(u => u.Addresses.Where(a => a.IsRowDeleted == false).Count > 0) && u.UserId == 5);