Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a problem with converting a native select statement with CASE statement using LINQ.
This is the native SQL which is working in SQL Server :
select
v.vehl_ContainerNo as cont_name, v.vehl_Name,
v.vehl_drivername, v.vehl_entrancedate, v.vehl_customsdec,
c.Capt_AR as VehicleState,
case
when v.vehl_rampid is null
then ''
else (select ramp_Name
from Ramp
where ramp_RampID = v.vehl_rampid)
end as cont_rampid
from
Vehicle v, Custom_Captions c
where
v.vehl_state = c.Capt_Code
and c.Capt_Family = 'vehl_state'
and v.vehl_ClearanceCompany = 471
I want to get the ramp_name:
if vehl_rampid is null then return an empty string
else do another select statement to get the ramp_name from the ramp table where vehl_rampid equals ramp_rampid.
when i use the following linq statement:
//List<qryRslt> query = (from v in db.Vehicles
// join cus in db.Custom_Captions on v.vehl_state equals cus.Capt_Code
// join ram in db.Ramps on v.vehl_rampid equals ram.ramp_RampID
// where
// cus.Capt_Family == "vehl_state" && v.vehl_Deleted == null && v.vehl_ClearanceCompany == p.pusr_CompanyId
// select new qryRslt
// {
// vehl_ContainerNo = v.vehl_ContainerNo,
// vehl_Name = v.vehl_Name,
// vehl_drivername=v.vehl_drivername,
// vehl_entrancedate=v.vehl_entrancedate,
// vehl_customsdec=v.vehl_customsdec,
// VehicleState=v.vehl_state,
// cont_rampid=v.vehl_rampid==null?" ":ram.ramp_Name
// }).ToList();
it gives me an unexpected result that differs from native sql statement written in sql server
How can I implement sql statement with another sql in case statement?
It depends what you returning. Let's assume you are trying to return class: MyClass
Then LINQ would looks something like:
List<MyClass> result = (from c in Vehicle
from x in Custom_Captions
join z in Ramp on c.vehl_rampId equals z.ramp_RampID
where c.vehl_state == x.Capt_Code
&& x.Capt_Family == 'vehl_state'
&& c.vehl_ClearanceCompany == 471
select new MyClass{
prop1 = c.vehl_rampid is null ? "" : z.ramp_Name
}).ToList();
Above code is using Object Initialiser to define object by filling it's all properties.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have ExpesnseIDVM ViewModel that only contains 1 variable ExpenseID to hold the last value from the database
public IEnumerable<ExpesnseIDVM> Profile(LoginVM loginVM)
{
var data = (from a in context.Employees
where a.Email == loginVM.Email
join b in context.Expenses on a.EmployeeId equals b.EmployeeId
select new ExpesnseIDVM()
{ ExpenseID = b.ExpenseId }).ToList().LastOrDefault();
return data;
}
I have a problem with the return type, what type of return type should I use to get the values
Four problems here:
SQL Server do not guarantee order of the items if you do not specify OrderBy
SQL do not have LastOrDefault direct translation. EF may try to reverse defined OrderBy and call FirstOrDefault - again OrderBy required
LastOrDefault returns one instance, not enumerable
ToList() loads whole table into the memory, but you need just one record, so do not use it.
Consider to rewrite your query in the following way:
public ExpesnseIDVM Profile(LoginVM loginVM)
{
var data = (from a in context.Employees
where a.Email == loginVM.Email
join b in context.Expenses on a.EmployeeId equals b.EmployeeId
orderby b.ExpenseId descending
select new ExpesnseIDVM()
{ ExpenseID = b.ExpenseId }).FirstOrDefault();
return data;
}
You have IQueryable?<T> as return value of the linq query, then you have .ToList() That makes EF to calculate the query, getting List<T> and finally .LastOrDefault() that returns single object of T.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have this code
var value = (from dc in _context.ContractDetails
where dc.EmployeeID == id
select dc.Amount);
return value;
}
is it acceptable to do Value.Sum();
You want to return the sum it looks like. Instead of having query be a decimal, just let it be what it wants (var, it's really IEnumerable<decimal>). Then you can return an aggregate on that. Sum for example
var query = from emp in Employees
join cd in ContractDetails
on emp.EmployeeID equals cd.EmployeeID
where cd.EmployeeID == id
select cd.Amount;
return query.Sum();
If this is all it does, then I also feel like you don't need to join at all, and it would be simpler to do
var query = from cd in ContractDetails
where cd.EmployeeID == id
select cd.Amount;
return query.Sum();
... unless you were using the join to test for the existence of an employee in the Employee table as a condition.
Your linq statement results in an IQueryable<Amount>, you would need to take that result and call Sum() on it to get the result you're seeking.
First, isn't there a navigation property you can use (i.e. Employee.ContracteDetails) instead of manually joining the two sets? For example,
var sum = _context.Employee
.Where( e => e.Id == id )
.Select( e => e.ContractDetails.Sum( cd => cd.Amount ) )
.SingleOrDefault();
Second, you're not using any information you need from Employee, even your where clause references ContractDetails alone; why start your query there? Work with _context.ContractDetails instead:
var sum = _context.ContractDetails
.Where( cd => cd.EmployeeId == id )
.Sum( cd => cd.Amount );
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
so i have this query in sql:
select (select ConfigItemDescripcion from SGRC_ConfigItem where ConfigId = 'SEGM' and ConfigItemId = SegmentoId) Segmento,
(select ConfigItemDescripcion from SGRC_ConfigItem where ConfigId = 'MRCA' and ConfigItemId = MarcaId) Marca,
Producto,
Familia
from sgrc_emisor
where EmisorCuenta = '3702406435'
I want to write the same query in a linq expression or a lambda expression.
Thanks for the help in advance
Finally i manage to come up with the query in linq, dont know how to do it in lambda, but it works fine.
var obj = (from emisor in _context.DbSetEmisores
where emisor.EmisorCuenta == cuenta
select new EmisorDto
{
Segmento =
((from itemConf in _context.ItemsDeConfiguracion
where itemConf.ConfigID == "SEGM" && itemConf.ConfigItemID == emisor.SegmentoId
select new { itemConf.ConfigItemDescripcion }).FirstOrDefault().ConfigItemDescripcion),
Marca =
((from itemConf in _context.ItemsDeConfiguracion
where itemConf.ConfigID == "MRCA" && itemConf.ConfigItemID == emisor.MarcaId
select new { itemConf.ConfigItemDescripcion }).FirstOrDefault().ConfigItemDescripcion),
Producto = emisor.Producto,
Familia = emisor.Familia,
SegmentoId = emisor.SegmentoId,
MarcaId = emisor.MarcaId,
}).FirstOrDefault();
When using LINQ you can use either Query syntax as shown in the LINQ below (If you are familiar with SQL then this looks more natural).
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq
The other option is to use Method syntax, and below is a short example. This allows for chaining of methods, biggest thing to keep in mind is "var" should be used, the return type is dynamic and the compiler will help you out a lot if you just use "var"
var items = _list.Where(x => x.Attribute1 == "NextField")
.Where(x => x.Attribute2 == "Something else");
Other things that hangs folks up sometimes is LINQ uses "delayed execution"
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hello I'm trying to transform this code from SQL to C# using Linq
The SQL code is like this:
SELECT N.Name,N.Unit,N.Typee,ID,NOTE
FROM Table_A N join Table_B A on (N.ID = A.ID)
join NotasQL G on ((N.Not1 = G.CODE) or (N.Not2 = G.CODE) )
join Attributes X on (A.AppID= X.AppID)
This Code is running fine in SQL with the expected result, but when I'm trying to replicate this on C# I don't know how to do the OR part, this is what I have so far:
var Select = (from A in context.Table_A
from B in context.Table_B
from E in context.NotasQLs
from D in context.Attributes
where (String.Compare(A.ID, B.ID, true) == 0 &&
String.Compare(B.AppID, D.AppID, true) == 0
&&
(String.Compare(A.Not1, E.CODE, true) == 0 ||
String.Compare(A.Not2, E.CODE, true) == 0))
I'm having an application runtime expired because the query is not selecting nothing, if I remove the or condition runs but I need the OR.
For translating SQL to LINQ query comprehension:
Translate FROM subselects as separately declared variables.
Translate each clause in LINQ clause order, translating monadic and aggregate operators (DISTINCT, TOP, MIN, MAX etc) into functions applied to the whole LINQ query.
Use table aliases as range variables. Use column aliases as anonymous type field names.
Use anonymous types (new { ... }) for multiple columns.
JOIN conditions that aren't all equality tests with AND must be handled using where clauses outside the join, or with cross product (from ... from ...) and then where
JOIN conditions that are multiple ANDed equality tests between the two tables should be translated into anonymous objects
LEFT JOIN is simulated by using into joinvariable and doing another from from the joinvariable followed by .DefaultIfEmpty().
Replace COALESCE with the conditional operator (?:)and a null test.
Translate IN to .Contains() and NOT IN to !...Contains().
Translate x BETWEEN low AND high to low <= x && x <= high.
SELECT * must be replaced with select range_variable or for joins, an anonymous object containing all the range variables.
SELECT fields must be replaced with select new { ... } creating an anonymous object with all the desired fields or expressions.
Proper FULL OUTER JOIN must be handled with an extension method.
So for your query,
var ans = from N in Table_A
join A in Table_B on N.ID equals A.ID
from G in NotasQL
where G.CODE == N.Not1 || G.CODE == N.Not2
join X in Attributes on A.AppID equals X.AppID
select new {
N.Name,
N.Unit,
N.Typee,
N.ID, // ??? not sure table for this column
G.NOTE // ??? not sure table for this column
};
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am rewriting a tool from old .net to .net 4.0 and am using Linq. I am new to Linq and became stuck when solving the following problem:
I have a table called UserInfo with all the columns needed. However, I need a specific data and need to do as follow but in Linq. Can someone please help me with Linq query syntax? Any help much be appreciated.
Thanks a lot in advance for any help with this matter.
SELECT DISTINCT a.liProviderKey
FROM UserInfo a INNER JOIN
UserInfo b ON a.strBusinessType = b.strBusinessType AND
(a.strCity = b.strCity AND a.strZip = b.strZip AND a.strState = b.strState AND
a.strCompanyName = b.strCompanyName AND (a.strDotNum = b.strDotNum OR
a.strFedTaxNum = b.strFedTaxNum OR
a.strPhone = b.strPhone)) OR
(a.strSSN = b.strSSN AND a.strLastName = b.strLastName AND a.strbusinessType='Consumer')
WHERE (b.liUserKey = #UserID AND a.fActive=1 AND a.fAuthenticated=1)
Using method syntax:
DataContext dc = new DataContext(ConnectionString);
var result = dc.UserInfos.Join(dc.UserInfos,
a => new { strBusinesssType == a.strBusinessType, ..., strSSN = a.strSSN },
b => new { strBusinesssType == b.strBusinessType, ..., strSSN = b.strSSN },
(a, b) => new { aTable = a, bTable = b })
.Where(o => o.bTable.liUserKey == #UserID && o.aTable.fActive == 1 && o.aTable.fAuthenticated == 1)
.Select(o => o.aTable.liProviderKey).Distinct();
Using query syntax:
var query = from a in UserInfos
join b in UserInfos on new { a.strBusinessType, ..., a.strSSN } equals new { b.strBusinessType, ..., b.strSSN }
where b.liUserKey == #UserID && a.fActive == 1 && a.fAuthenticated == 1
select a.liProviderKey;
query = query.Distinct();
If you want a complex comparison, you'll have to do the join in the where clause. Here you would remove the join and replace it with a second from (again, query syntax):
var query = from a in UserInfos
from b in UserInfos
where b.liUserKey == #UserID && a.fActive == 1 && a.fAuthenticated == 1 &&
((a.strBusinessType == b.strBusinessType) && ([rest of your conditions]))
select a.liProviderKey;
query = query.Distinct();