how to use joining with LinQ To Entity [closed] - c#

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 );

Related

function Return LastOrDefault() [closed]

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.

how to write a nested Sql query in Linq [closed]

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"

Can I optimize my LINQ query? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I'm trying to create my very first database queries using LINQ. For practice I'm using the Adventure Works 2014 database from Microsoft.
DB Diagram.
One of my first goals is to create static method for DataService returning a list of all products for given vendor's name. It looks like my method returns the correct data, but I think it is very poorly optimized. Can I improve it somehow?
public static List<Product> GetProductsByVendorName(string vendorName)
{
AdventureWorksDatabaseClassDataContext dc = new AdventureWorksDatabaseClassDataContext();
int vendorID = dc.Vendors.Where(vendor => vendor.Name == vendorName).Select(vendor => vendor.BusinessEntityID).First();
IEnumerable <ProductVendor> productsVendor = dc.ProductVendors;
IEnumerable<int> selectedProductsID = from ProductVendor productVendor in productsVendor
where productVendor.BusinessEntityID == vendorID
select productVendor.ProductID;
IEnumerable<Product> products = dc.Products;
IEnumerable<Product> selectedProducts = from Product p in products
where selectedProductsID.Contains(p.ProductID)
select p;
return selectedProducts.ToList();
}
You should use joins on database side to avoid transferring data over network and loading entities into memory:
from v in dc.Vendors
join pv in dc.ProductVendors on v.BusinessEntityID equals v.BusinessEntityID
join p in dc.Products on p.ProductID equals pv.ProductID
where v.Name == vendorName
select p
Note that if you have proper setup of navigation properties, then this query can look like
dc.Vendors.Where(v => v.Name == vendorName)
.SelectMany(v => v.ProductVendors.Select(pv => pv.Product))

Convert SQL statement to LINQ with case condition [closed]

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.

restrict num of items loaded in navigation property

I have the following query in Linq:
var query = from question in context.Questions.Include("QAnswers")
join answer in context.Answers
on question.id equals answer.qst
where answer.user == param_userID
select question;
return query.toList();
The problem is that it doesn't load the "QAnswers" navigation property at all.
Is there any way in Entity Framework to return the entity and restricted result set in its navigation property?
Ps.
I'm using EF4 if it's important
If I understood it correctly, this should be enough:
context.Questions.Include("QAnswers").Where(q => q.QAnswers.Any(a => a.user == param_userID));
These are questions where specific user answered. There is no need for joins.
EDIT
context.Questions.Where(q => q.QAnswers.Any(a => a.user == param_userID)).Select(q => new { Question = q, Answers = q.QAnswers.Where(a => a.user == param_userID) }).ToList();
This will return question and only specific user's answers.

Categories

Resources