How to use and if statement in linq Entity framework c# - c#

I am declaring this variable to get data from my database(example)
var products = _context.Products();
and I need to use like this example
if(ctId == -1)
{
// get project list
var products = _context.Products().where(a => a.categoryId == 2);
}
else
{
//get category list
var products = _context.Products().where(a => a.categoryId == 1);
}
but my problem how to declare var products
to using like this
if(ctId == -1)
{
// get project list
products = _context.Products().where(a => a.categoryId == 2);
}
else
{
//get category list
products = _context.Products().where(a => a.categoryId == 1);
}

To the initial problem, you would declare an IQueryable<Product> outside the if scope
IQueryable<Product> products = null;
if(ctId == -1)
products = _context.Products().where(a => a.categoryId == 2);
else
products = _context.Products().where(a => a.categoryId == 1);
However, you could also use a ternary conditional operator
The conditional operator ?:, also known as the ternary conditional
operator, evaluates a Boolean expression and returns the result of one
of the two expressions, depending on whether the Boolean expression
evaluates to true or false.
The syntax for the conditional operator is as follows:
condition ? consequent : alternative
Example
var id = ctId == -1 ? 2 : 1;
var products = _context.Products().where(a => a.categoryId == id);
or potentially
var products = _context.Products().where(a => a.categoryId == (ctId == -1 ? 2 : 1));

Related

Neglect variable from Query in entity framework where condition C#

public ActionResult sortFilteredItem(string sortByValue,string brand,string category,int price=0 )
{
var sortedData = (dynamic)null;
if (sortByValue != "")
{
if(sortByValue == "ltoh")
{
sortedData = DB.Prouducts.where(x=> x.brandName == brand & x.catName == category & x.price == price).ToList();
}
}
return View(sortedData);
}
how i can neglect if price=0 from query means that it does not make any impact on EF query because if price=0 the query does not returning expected output.Because i have not any record that has 0 price so the query is always returning null.
if(price != 0)
{
sortedData = DB.Prouducts.where(x=> x.brandName == brand & x.catName == category & x.price == price).ToList();
}
else
{
sortedData = DB.Prouducts.where(x=> x.brandName == brand & x.catName == category).ToList();
}
i have tried like this it is working good but that is lengthy process.if i have 4 or 5 more variable that,s optional so it is necessary to check null value first for working.Any recommendation ?
You can use the fllowing logic;
sortedData = DB.Prouducts.where(x=> x.brandName == brand
&& x.catName == category
&& (price == 0 || x.price == price)) //use this approach for every optional param
.ToList();
What you can do is apply filters only if the condition holds. Let's say you need to check catName and price. So:
var query = DB.Prouducts.Where(x=> x.brandName == brand);
if (category != null)
{
query = query.Where(x => x.catName == category);
}
if (price != 0)
{
query = query.Where(x => x.price == price)
}
sortedData = query.ToList();
Obviously you'll need one "if" per filter, but it is much better than considering all possible combinations.

Difference between LINQ Lambda and SQL statement

I have the following lambda statement:
var resources = Db.Resource.Where(w => w.ResValue.Any(a => a.ApplicationFk == applicationPk) && w.CategoryFk == (categoryId ?? w.CategoryFk ) && w.IsEditable);
if (cultureIdsMissing!= null)
{
resources = resources.Where(w => w.ResValue.Any(a => cultureIdsMissing.Any(aa => aa == a.CultureFk) && a.Value == string.Empty));
}
This is not returning the result which I want, which is returned by:
SELECT Resource.ResourcePk, Resource.CategoryFk, Resource.Name, Resource.IsEditable, ResValue.ApplicatieFk, ResValue.CultureFk, ResValue.Value
FROM Resource
INNER JOIN ResValue ON Resource.ResourcePk = ResValue.ResourceFk
WHERE (ResValue.ApplicatieFk = 6)
AND (Resource.IsEditable = 1)
AND (ResValue.Value = '')
AND (ResValue.CultureFk = 1 OR ResValue.CultureFk = 2)
Not that cultureIdsMissing is a List containing both the numbers 1 and 2.
What am I missing or doing wrong with the lambda query?
I think you have to remove && w.CategoryFk == (categoryId ?? w.CategoryFk ) from your linq lemda expression. if categoryId = 1 then it will take only records with value 1. So try after remove that. Your linq code should be this.
var resources = Db.Resource.Where(w => w.ResValue.Any(a => a.ApplicationFk == applicationPk)&& w.IsEditable);
if (cultureIdsMissing!= null)
{
resources = resources.Where(w => w.ResValue.Any(a => cultureIdsMissing.Any(aa => aa == a.CultureFk) && a.Value == string.Empty));
}
You should take it from your sql statement :
Db.Resource
.Join(Db.ResValue
, rs => rs.ResourcePk
, resV => resv.resourceFk
, (rs, resv) => new { res = rs, resV = resV })
.Where(w => w.resv.ApplicatieFk == 6
&& w.res ==1
&& resv.Value == string.empty()
&& (resv.CultureFk == 1 || resv.CultureFk == 2))
It's not tested so maybe it won't work on first try.
I would translate the SQL to query comprehension syntax. In general, convert phrases in query comprehension order, use table aliases as range variables (or create range variables), and put unary/overall aggregate functions (such as TOP, DISTINCT or SUM) as function calls outside the whole query. For your SQL,
var ans = from r in Resource
where r.IsEditable == 1
join rv in ResValue on r.ResourcePk equals rv.ResourceFk
where rv.ApplicatieFk == 6 && rv.Value == "" && (rv.CultureFk == 1 || rv.CultureFk == 2)
select new { r.ResourcePk, r.CategoryFk, r.Name, r.IsEditable, rv.ApplicatieFk, rv.CultureFk, rv.Value };

Dynamic Where clause in Lambda expression

I have some filter parameters in the Controller of an ASP.NET MVC project and I need to create Where clause dynamically according to these parameters. If isActive parameter is true, it will get the records having the StatusId = 1. There are also userName and labId parameters in the method that should be matched in the Where clause.
public ActionResult GetStudents(int labId, string userName, bool isAll)
{
var allRecords = repository.Students;
//If isAll, get all the records having StatusId = 1
var result = allRecords.Where(m => (isAll) || m.StatusId == 1);
//???
}
I use the filter above, but I have no idea what is the most suitable way (conventions) for multiple parameters in order to fetch the result fast. Any idea?
Note: I want to filter for all of three parameters and Where clause should contain all of the combinations according to the parameter's values (also is null or empty).
var predicate = PredicateBuilder.False<Record>();
if(isAll)
predicate = predicate.AND(d => d.StatusId ==1);
predicate = predicate.AND(d => d.labID == labid && d.username = username);
return allRecords.Where(predicate);`
You can use a predicate builder
You can concatenate linq-methods as they all return an IEnumerable<T> and are combined using something like an SQL-And (dependinng on what LINQ-provider you use):
IEnumerable<Student> result = allRecords;
if(labelId.HasValue)
result = result.Where(x => x.LabelId == labelId);
else
result = result.Where(x => x.LabelId == 0); // or whatever your default-behaviour is
if(isAll)
result = result.Where(x => x.StatusId == 1);
else
result = result.Where(x => x.StatusId == 0); // or whateever your default-behaviour is when isAll is false
if(!String.IsNullOrEmpty(userName))
result = result.Where(x => x.Name == userName);
else
result = result.Where(x => x.Name == "Claus"); // or whatever the default-behaviour is when the param isnĀ“t set
Do like this
public ActionResult GetStudents(int labId, string userName, bool isAll)
{
var allRecords = repository.Students;
//If isAll, get all the records having StatusId = 1
if (isAll)
{
var result = allRecords.Where(m => m.StatusId == 1 && m.UserName == userName && m.LabId == labId);
}
else
{
// do else things
}
}
you need something like below
public ActionResult GetStudents(int labId, string userName, bool isAll)
{
var allRecords = repository.Students;
//If isAll, get all the records having StatusId = 1
if (isAll)
{
var result = allRecords.Where(m => m.StatusId == 1
&& m.LabId == labId
&& m.UserName == username);
//or
var result = from record in allRecords
where record != null &&
record.StatusId == 1
&& !string.IsNullOrWhiteSpace(record.UserName)
&& record.UserName.Equals(username)
&& record.Labid = labId
select record;
}
else
{
// do else things
}
}

Merge two Ordering Results into one result in linq with C#

I order two types of query. I want to show the result as one. if the first query and second query have count these both are merge and show the results of one. So i have created 3 list like jobs, jobs1, jobs2. I am getting values into jobs1 and jobs2. Then i have assigned using union into jobs3
Code
IQueryable<Job> jobs = _repository.GetJobs();
IQueryable<Job> jobs1 = _repository.GetJobs();
IQueryable<Job> jobs2 = _repository.GetJobs();
List<int> lstId = null;
List<int> lstUpdatedListId = null;
List<int> lstConId=null;
var order = _db.GetOrderDetails().Where(od => od.Masters.Id != null && od.OrderId == od.Master.OrderId && od.Master.Status == true && od.ValidityTill.Value >= currentdate).OrderByDescending(od => od.ValidityTill).Select(ord => ord.Master.Id.Value);
var order1 = _vasRepository.GetOrderDetails().Where(od => od.Masters.ConId != null && od.OrderId == od.Masters.OrderId && od.Masters.PaymentStatus == true && od.ValidityTill.Value >= currentdate).OrderByDescending(od => od.ValidityTill).Select(ord => ord.Masters.ConId.Value);
var updatedVacancyList = _repository.GetJobs().Where(c => c.UpdatedDate != null && updateFresh <= c.UpdatedDate).Select(c => c.Id);
if (order1 .Count() > 0)
{
lstConId = order1.ToList();
Func<IQueryable<Job>, IOrderedQueryable<Job>> orderingFunc = query =>
{
if (order1.Count() > 0)
return query.OrderByDescending(rslt => lstConId.Contains(rslt.Con.Id)).ThenByDescending(rslt=>rslt.CreatedDate);
else
return query.OrderByDescending(rslt => rslt.CreatedDate);
};
jobs1 = orderingFunc(jobs);
}
if (order.Count() > 0)
{
lstId = order.ToList();
lstUpdatedJobsListId = updatedVacancyList.ToList();
Func<IQueryable<Job>, IOrderedQueryable<Job>> orderingFunc = query =>
{
if (order.Count() > 0)
return query.OrderByDescending(rslt => lstId.Contains(rslt.Id)).ThenByDescending(rslt => lstUpdatedJobsListId.Contains(rslt.Id)).ThenByDescending(rslt=>rslt.CreatedDate);
if (updatedVacancyList.Count() > 0)
return query.OrderByDescending(rslt => lstUpdatedJobsListId.Contains(rslt.Id)).ThenByDescending(rslt => rslt.UpdatedDate);
else
return query.OrderByDescending(rslt => rslt.CreatedDate);
};
jobs2 = orderingFunc(jobs);
}
jobs = jobs1.Union(jobs2);
and i am getting an error while run the application as follows,
The text data type cannot be selected as DISTINCT because it is not comparable.
I need help to rectify this issue. I want to order in descending also.
One of your columns in Database is "Text" type. Convert it to varchar(MAX)

LINQ: How can I shorten my code?

I have done some LINQ, it works great but I'm not a fan of this type of coding, I would like to shorten it down, but not quite sure how to.
Does anyone know how I can shorten this section of code? I've heard of predicates before but not quite sure how to implement them?
List<Voucher> list = new List<Voucher>();
if (String.IsNullOrEmpty(Search.SearchText) && Search.Status == 0)
{
list = (from voucherslist in db.Vouchers
//where voucherslist.Status != (int)VoucherStatus.Removed
select voucherslist)
.Take(100)
.ToList();
}
if (!String.IsNullOrEmpty(Search.SearchText) && Search.Status ==0)
{
list = (from voucherslist in db.Vouchers
where voucherslist.Title.Contains(Search.SearchText)
select voucherslist).Take(100).ToList();
}
if (String.IsNullOrEmpty(Search.SearchText) && Search.Status > 0)
{
list = (from voucherslist in db.Vouchers
where voucherslist.Status == Search.Status
select voucherslist).Take(100).ToList();
}
if (!String.IsNullOrEmpty(Search.SearchText) && Search.Status > 0)
{
list = (from voucherslist in db.Vouchers
where voucherslist.Status == Search.Status
&& voucherslist.Title.Contains(Search.SearchText)
select voucherslist).Take(100).ToList();
}
// Convert
ret = VouchersConverter.Convert(list);
// Get Business Details
foreach (ENT_Voucher item in ret)
item.BusinessDetails = this._businessesBLL.GetBusinessDataByID(item.BusinessID);
// Refine and sort
ret = ret.Where(x=>x.BusinessDetails.Accept == true)
.OrderByDescending(x => x.Status.Equals(1))
.ThenByDescending(x => x.StartDate).ToList();
To remove the repetition, first set up your list.
list = (from voucherslist in db.Vouchers
//where voucherslist.Status != (int)VoucherStatus.Removed
select voucherslist);
Then add the title search if you need it:
if (!String.IsNullOrEmpty(Search.SearchText))
{
list = list.Where(x => x.Title.Contains(Search.SearchText));
}
And the status search:
if (Search.Status > 0)
{
list = list.Where(x => x.Status == Search.Status);
}
And finally, take your 100 and flatten it to a list.
list = list.Take(100).ToList();
The thing to bear in mind is that this will not actually construct and execute the SQL query until the .ToList() call, and the SQL that will be executed will contain all of the filtering you have concatenated together.
Your current logic looks a bit broken to me, but I suspect you want:
var query = db.Vouchers;
if (...)
{
query = query.Where(v => v.Title.Contains(Search.SearchText);
}
if (...)
{
query = query.Where(v => v.Status == Search.Status);
}
// etc
List<Voucher> list = query.Take(100).ToList();
Using multiple calls to Where will effectively apply an "AND" on all the filters.

Categories