Add Conditional Join Dynamically with Linq - asp.net

I have a basic search control which lists companies from a CRM depending on predefined search/filtering criteria supplied by dropdowns. The default selection is "ALL" for each DropDown, otherwise the user chooses a specific item(s). I'd like to be able to construct a Linq query dynamically based on the selections. Out of the 5 selectors they supply values that I can match against the Company table, but two of the selectors (if either or both are chosen) would require a join or joins, else no action should be taken again the base result set. I hope this makes sense.
I'm not sure how to do this effectively. Here is my code:
private void Search()
{
EnergyPubsCRMDataContext dc = new EnergyPubsCRMDataContext();
var results = (from c in dc.Companies
select c);
//only create the join if the selected index > 0
if (ddlIndustry.SelectedIndex > 0)
{
//A company can be in 1 or more industries, thus here I want to join
//with the CompanyIndustry table and have a WHERE clause to match on the ddlIndustry.SelectedValue
}
//only create the join if the selected index > 0
if (ddlServices.SelectedIndex > 0)
{
//A company can offer 1 or more services. Here I want to join to the CompanyService table
//on the CompanyID and have a WHERE clause to match the ddlServices.SelectedValue
}
//These work OK to shape the overal query further (they don't need joins)
if (ddlCountry.SelectedIndex > 0)
results = results.Where(c => c.CountryID == Convert.ToInt32(ddlCountry.SelectedValue));
if (ddlStateRegion.SelectedIndex > 0)
results = results.Where(c => c.StateRegionID == Convert.ToInt32(ddlStateRegion.SelectedValue));
if (ddlAccountManagers.SelectedIndex > 0)
{
Guid g = new Guid(ddlAccountManagers.SelectedValue);
results = results.Where(c => c.UserId == g);
}
results = results.OrderBy(c => c.CompanyName);
//Bind to Grid....
}

if (ddlIndustry.SelectedIndex > 0)
{
//A company can be in 1 or more industries, thus here I want to join
//with the CompanyIndustry table and have a WHERE clause to match on the ddlIndustry.SelectedValue
results = results.Where(c => c.CompanyIndustry.IndustryID == ddlIndustry.SelectedValue);
}
Assuming you have correct foreign keys in your database/DBML.
This will generate the join implicitly.

I had very similar issue and no foreign keys I could leverage.
My solution would translate to something like this:
results = results
.Join(dc.CompanyIndustry, c => c.CompanyID, ci => ci.CompanyID, (c, ci) => new { c, ci.IndustryID })
.Where (a => a.IndustryID == ddlIndustry.SelectedValue)
.Select(a => a.c);
Basically:
1) first we create a join, with a projection that gives us IndustryID (join)
2) we filter based on IndustryID (where)
3) we return original anonymous type, so that we can modify original query (select)

Related

Database returns 0 instead of selected value in ASP.NET MVC

I would like to retrieve the userInfoId from the database and pass it into var where the Login username is Kenny. However, the value returned to u was 0 instead of the desired value. I have tried selecting another username but the result was still the same.
var u = Database.UserInfo
.Where(userinfo => userinfo.LoginUserName == "BEN")
.Select(x=> x.UserInfoId)
.FirstOrDefault();
Put some breakpoints and see what you have inside u, Use the query below and you should be good to go. Make sure the table/column names are correct according to your db.
int userInfoId = (from x in context.UserInfo
where x.LoginUserName == "Kenny"
select x.UserInfoId).SingleOrDefault());
if (userInfoId > 0){
// user exists and do what you wish to next
}
else {
// user does not exist
}

Crossfilter grouping filtered keys

I have some json, for examle:
data = {
"name":"Bob","age":"20",
"name":"Jo","age":"21",
"name":"Jo","age":"22",
"name":"Nick","age":"23"
}
Next, I use crossfilter, create dimension and filter it:
let ndx = crossfilter(data);
let dim = ndx.dimension(d => d.name).filter(d !== "Jo");
//try to get filtered values
let filtered = dim.top(Infinity); // -> return 2 values where 'name'!='Jo'
//"name":"Bob","age":"20"
//"name":"Nick","age":"23"
let myGroup = dim.group(d => {
if(d === 'Jo') {
//Why we come here? This values must be filtered already
}
})
How can I filter my dimension and don't have these values on 'dim.group'?
Not sure what version you are using, but in the current version of Crossfilter, when a new group is created all records are first added to the group and then filtered records are removed. So the group accessor will be run at least once for all records.
Why do we do this? Because for certain types of grouping logic, it is important for the group to "see" a full picture of all records that are in scope.
It is possible that the group accessor is run over all records (even filtered ones) anyway in order to build the group index, but I don't remember.

Entity Framework nested lambda query

In Linq2Sql, it was possible to do a query such as:
using (var db = GetDataContent())
{
var query = from p in db.Brands
where p.Deleted == false
select new BrandImageSummary
{
BrandID = p.BrandID,
BrandUrl = p.BrandUrl,
Description = p.Description,
MetaDescription = p.MetaDescription,
MetaKeywords = p.MetaKeywords,
MetaTitle = p.MetaTitle,
BrandImageUrl = (from p2 in db.SiteImages where p2.FileTypeID == 5 && p2.ForeignID == p.BrandID && p2.Deleted == false orderby p2.Rank select p2.Filename).FirstOrDefault(),
Deleted = p.Deleted,
SupplierCode = p.SupplierCode,
Title = p.Title,
Website = p.Website
};
return query.ToList();
}
With BrandImageUrl being a nested select. Howerver in entity framework, I seem to get the error:
Unable to create a constant value of type 'SiteImage'. Only primitive
types or enumeration types are supported in this context.
Is there a way to do this in entity framework?
The idea of the query is to get one brand image, if I was to join, and there was multiple images, I would get multiple rows and I do not want this.
I am using Entity Framework 5.
Thanks for your help
You should create a one-to-many relation in your model classes.
You can then write
BrandImageUrl = p.BrandImages
.Where(i => i.FileTypeID == 5 && !i.Deleted)
.OrderBy(i => i.Rank)
.Select(i => i.FileName)
.FirstOrDefault()

Can't use foreach on a anonymous type

I have the code below where I am trying to go through the child questions of my qestAires anonymous type. When I get to the foreach loop i get the error:
foreach statement cannot operate on
variables of type 'Question' because
'Question' does not contain a public
definition for 'GetEnumerator'
What do I need to do differently to get around this?
var questAires = (from qs in dc.Questionnaires
from q in dc.Questions.Where(t => t.QuestionnaireId == qs.QuestionnaireID)
from r in dc.Responses.Where(qr => qr.QuestionID == q.QuestionId).DefaultIfEmpty()
where qs.QuestionnaireID == QuestionnaireId
select new
{
qs.Description,
Questions = q,
Responses = r
}).Single();
foreach(var question in questAires.Questions)
{
}
questAires.Questions will only resolve to a single question, and you will get one questAires object for each question (which will cause .Single() to throw).
I guess you want something like this:
var questAires = (from qs in dc.Questionnaires
select new {
qs.Description,
Questions = from q in dc.Questions where q.QuestionnaireId == qs.QuestionnaireID
select new {
Question = q,
Response = (from r in dc.Responses where r.QuestionID == q.QuestionId select r).DefaultIfEmpty()
}
}).Single()
q actually resolves to a single item from the enumerable dc.Questions.Where(...), so yeah, you're only going to get a single item - not an enumerable - for Questions.

LINQ sorting, doesn't work

I have a LINQ query like this:
from i in _db.Items.OfType<Medium>()
from m in i.Modules
from p in m.Pages
where i != null && i.Type == 1 && i.Published == true && p.PageId == 2
select p
I use the query like this because I have strongly typed view (ASP.NET MVC).
I need to have items sorted by the i.Sort property. orderby i.Sort and i.OrderBy(it => it.Sort) doesn't work. How can I fix this?
When sorting with Linq you usually give OrderBy a property, and eventually an IComparer, not a sorting function. For example:
class Person {
public int Age {get; set;}
}
public static void Main() {
var ps = new List<Person>();
ps.Add(new Person{Age = 1});
ps.Add(new Person{Age = 5});
ps.Add(new Person{Age = 3});
var sorted = ps.OrderBy(p => p.Age);
foreach(p in sorted) {
Console.WriteLine(p.Age);
}
}
Here Linq will know how to correctly sort integers.
Without giving more context (such as what exactly is i.Sort, what is its purpose, what do you want to do with it), it would be difficult to be more specific to your problem.
However, I'm pretty sure you are misunderstanding OrderBy: you should give it a lambda expression that identifies a property of the objects contained in your sequence, and then Linq will sort your sequence according to the usual order of the type of that property (or according to another order you define for that type, by using IComparer).
Let's say your Pages include page-numbers among their properties. Let's pretend this property is called "pagenumber". You would then add the following 'orderby' line between the 'where' and 'select' lines.
// (snip...)
where i != null && i.Type == 1 && i.Published == true && p.PageId == 2
orderby p.pagenumber
select p
Or maybe you don't have page numbers, but only page titles. You would do nearly the same thing:
where i != null && i.Type == 1 && i.Published == true && p.PageId == 2
orderby p.title
select p
Just from reading your code, I can't tell what criteria should be used for sorting. You need some kind of ordered element, an id number, a page number, or some text can be alphabetized.
from i in _db.Items.OfType<Medium>().OrderBy(x => x.Sort)
...

Resources