SubSonic 3, build dynamic or expression at runtime - c#

I have a situation where I have to dynamically build a linq query based on user selections.
If I had to dynamically generate sql I could do it this way:
var sb = new StringBuilder();
sb.AppendLine("SELECT * FROM products p");
sb.AppendLine("WHERE p.CategoryId > 5");
// these variables are not static but choosen by the user
var type1 = true;
var type2 = true;
var type3 = false;
string type1expression = null;
string type2expression = null;
string type3expression = null;
if (type1)
type1expression = "p.productType1 = true";
if (type2)
type2expression = "p.productType2 = true";
if (type3)
type3expression = "p.productType3 = true";
string orexpression = String.Empty;
foreach(var expression in new List<string>
{type1expression, type2expression, type3expression})
{
if (!String.IsNullOrEmpty(orexpression) &&
!String.IsNullOrEmpty(expression))
orexpression += " OR ";
orexpression += expression;
}
if (!String.IsNullOrEmpty(orexpression))
{
sb.AppendLine("AND (");
sb.AppendLine(orexpression);
sb.AppendLine(")");
}
// result:
// SELECT * FROM products p
// WHERE p.CategoryId > 5
// AND (
// p.productType1 = true OR p.productType2 = true
// )
Now I need to create a linq query the same way.
This works well with subsonic
var result = from p in db.products
where p.productType1 == true || p.productType2 == true
select p;
I tried it with PredicateBuilder http://www.albahari.com/nutshell/predicatebuilder.aspx but that throws an exception with subsonic.
var query = from p in db.products
select p;
var inner = PredicateBuilder.False<product>();
inner = inner.Or(p => p.productType1 == true);
inner = inner.Or(p => p.productType2 == true);
var result = query.Where(inner);
the exception that is thrown: NotSupportedException: The member 'productType1' is not supported
at SubSonic.DataProviders.MySQL.MySqlFormatter.VisitMemberAccess.
Anybody has an idea how to get this query to work:

Maybe Dynamic LINQ will be helpful?

Here is an usage example, as requested by geocine.
It requires Dynamic Linq.
var productTypes = new int[] {1,2,3,4};
var query = from p in db.products
select p;
if (productTypes.Contains(1))
query.Add("productType1 = #0");
if (productTypes.Contains(2))
query.Add("productType2 = #0");
if (productTypes.Contains(3))
query.Add("productType3 = #0");
if (productTypes.Contains(4))
query.Add("productType4 = #0");
if (productTypes.Count > 0)
{
string result = String.Join(" OR ", productTypes);
query = query.Where("(" + result + ")", true);
}
var result = from p in query
select new {Id = p.ProductId, Name = p.ProductName };
it looks akward but it works.

Related

MongoDB Linq query in C# with filters

I am trying to do a LINQ query on several Mongo collections. All the collections have to be joined based on ApplicationId and an outer Join has to be done - so that persons that have no statuses are returned as well.
The JOIN part and everything around it works as expected. The problem is that when I add a filter to one of the collections, the whole thing breaks
An exception of type 'System.ArgumentException' occurred in System.Linq.Expressions.dll but was not handled in user code: 'Expression of type 'System.Collections.Generic.IEnumerable`1[CDM.Person]' cannot be used for parameter of type 'System.Linq.IQueryable`1[CDM.Person]' of method 'System.Linq.IQueryable`1[CDM.Person] Where[Person](System.Linq.IQueryable`1[CDM.Person], System.Linq.Expressions.Expression`1[System.Func`2[CDM.Person,System.Boolean]])''
Here is my query
var applications = _dbContext.GetCollection<Application>(typeof(Application).Name).AsQueryable().Where(
x => x.OrganizationID == TokenContext.OrganizationID);
var persons = _dbContext.GetCollection<Person>(typeof(Person).Name).AsQueryable().Where(p =>p.FirstName == "j");
var statuses = _dbContext.GetCollection<ApplicationStatus>(typeof(ApplicationStatus).Name).AsQueryable();
var mortgages = _dbContext.GetCollection<Mortgage>(typeof(Mortgage).Name).AsQueryable();
var statusQuery = from a in applications
join p in persons on a.ApplicationID equals p.ApplicationID
join s in statuses on a.ApplicationID equals s.ApplicationID into pas
join m in mortgages on a.ApplicationID equals m.ApplicationID into morgs
from subWHatever in pas.DefaultIfEmpty()
select new ApplicationStatusProjection
{
ApplicationId = a.ApplicationID,
FirstName = p.FirstName,
LastName = p.Surname,
Prefix = p.Prefix,
DateOfBirth = p.DateOfBirth,
Initials = p.Initials,
PostalCode = p.Addresses.First().PostalCode,
MortgageAmount = morgs.Sum(i => i.MortgageTotal) ?? 0,
StatusExpireAt = subWHatever.ExpireAt ?? DateTime.MinValue,
StatusMessageText = subWHatever.MessageText ?? "",
StatusMessage = subWHatever.MessageStatus ?? ""
};
if (!String.IsNullOrEmpty(orderBy))
{
statusQuery = statusQuery?.OrderBy(orderBy);
}
if (nrOfRecords != null)
{
statusQuery = statusQuery?.Take(nrOfRecords.Value);
}
// Execute the query
var result = statusQuery?.ToList();
return result;
I followed the guidelines here https://mongodb.github.io/mongo-csharp-driver/2.6/reference/driver/crud/linq/ and I also tried this
var statusQuery =
from a in applications
join p in persons on a.ApplicationID equals p.ApplicationID into pa
from paObject in pa.DefaultIfEmpty()
join s in statuses on paObject.ApplicationID equals s.ApplicationID into pas
But I got the same error as before.
Thank you in advance.
So after may tryouts I have discovered that you cannot filter before the join because of the way the LINQ query is translated to Mongo query.
The fix for this is to have the filtering afterwards, on the statusQuery object. In that case, the filtering has to happen on the projected object (so a new filter is needed).
See below how I solved it:
//get collections
var applications = _dbContext.GetCollection<Application>(typeof(Application).Name).AsQueryable().Where(
x => x.OrganizationID == TokenContext.OrganizationID);
var persons = _dbContext.GetCollection<Person>(typeof(Person).Name).AsQueryable();
var statuses = _dbContext.GetCollection<ApplicationStatus>(typeof(ApplicationStatus).Name).AsQueryable();
var mortgages = _dbContext.GetCollection<Mortgage>(typeof(Mortgage).Name).AsQueryable();
//query
var query = from a in applications
join p in persons on a.ApplicationID equals p.ApplicationID
join s in statuses on a.ApplicationID equals s.ApplicationID into applicationStatusView
join m in mortgages on a.ApplicationID equals m.ApplicationID into morgs
from subStatus in applicationStatusView.DefaultIfEmpty()
select new ApplicationStatusProjection
{
ApplicationId = a.ApplicationID,
FirstName = p.FirstName,
LastName = p.Surname,
Prefix = p.Prefix,
DateOfBirth = p.DateOfBirth,
Initials = p.Initials,
Addresses = p.Addresses ?? new List<Address>(),
PostalCode = p.Addresses.First().PostalCode,
MortgageAmount = morgs.Sum(i => i.MortgageTotal) ?? 0,
StatusExpireAt = subStatus.ExpireAt ?? DateTime.MinValue,
StatusMessageText = subStatus.MessageText ?? "",
StatusMessage = subStatus.MessageStatus ?? "",
StatusDate = subStatus.StatusDate
};
//filter & order
var filteredResult = ApplyFilters(query, searchCriteria);
if (!String.IsNullOrEmpty(orderBy))
{
filteredResult = filteredResult?.OrderBy(orderBy);
}
if (nrOfRecords != null)
{
filteredResult = filteredResult?.Take(nrOfRecords.Value);
}
// Execute the query
var result = filteredResult?.ToList();
return result;
And applying the filters (there is probably a smarter way to do this):
private IQueryable<ApplicationStatusProjection> ApplyFilters(IQueryable<ApplicationStatusProjection> query, ApplicationStatusProjectionSearch searchCriteria)
{
if (!string.IsNullOrEmpty(searchCriteria.FirstName))
{
query = query.Where(x => x.FirstName.ToLower().StartsWith(searchCriteria.FirstName));
}
if (!string.IsNullOrEmpty(searchCriteria.LastName))
{
query = query.Where(x => x.LastName.ToLower().StartsWith(searchCriteria.LastName));
}
if (!string.IsNullOrEmpty(searchCriteria.PostalCode))
{
query = query.Where(x => x.Addresses.Any(a => a.PostalCode.ToLower().StartsWith(searchCriteria.PostalCode)));
}
//other irrelevant filters
return query;
}

How to apply multiple optional filters in a LINQ query

I have a page where user can select any number of search filters to apply search
When user clicks on search, these parameters are passed to my GetIndicatorData method to perform the query. However, it doesn't seem to work for me.
Here is my code
public static List<tblindicators_data_custom> GetIndicatorsData(string status, int service_id, int operator_id, string year, string frequency)
{
var date = Convert.ToDateTime(year + "-01-01");
int[] numbers = status.Split(',').Select(n => int.Parse(n)).ToArray();
var ict = new ICT_indicatorsEntities();
var result = from ind in ict.tblindicators_data
join ser in ict.tblservices on ind.service_id equals ser.Id
join oper in ict.tbloperators on ind.operator_id equals oper.Id
where numbers.Contains(ind.status) && (ind.date_added.Year == date.Year)
select new
{
ind.Id,
ind.service_id,
ind.survey_id,
ind.operator_id,
ind.type,
ind.date_added,
ind.quater_start,
ind.quater_end,
ind.status,
ind.month,
service = ser.name,
operator_name = oper.name
};
List<tblindicators_data_custom> data = new List<tblindicators_data_custom>();
foreach (var item in result)
{
tblindicators_data_custom row = new tblindicators_data_custom();
row.Id = item.Id;
row.survey_id = item.survey_id;
row.service_id = item.service_id;
row.service_name = item.service;
row.operator_id = item.operator_id;
row.operator_name = item.operator_name;
row.date_added = item.date_added;
row.quater_start = item.quater_start;
row.type = item.type;
row.quater_end = item.quater_end;
row.month = item.month == null? DateTime.Now:item.month;
row.status = item.status;
data.Add(row);
}
return data;
}

Listing in WCF Entity

I have a problem with LINQ query (see comment) there is a First method and it only shows me the first element.
When I write in the console "Sales Representative" it shows me only the first element of it as in
I would like to get all of data about Sales Representative. How can I do it?
public PracownikDane GetPracownik(string imie)
{
PracownikDane pracownikDane = null;
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
//Employee matchingProduct = database.Employees.First(p => p.Title == imie);
var query = from pros in database.Employees
where pros.Title == imie
select pros;
// Here
Employee pp = query.First();
pracownikDane = new PracownikDane();
pracownikDane.Tytul = pp.Title;
pracownikDane.Imie = pp.FirstName;
pracownikDane.Nazwisko = pp.LastName;
pracownikDane.Kraj = pp.Country;
pracownikDane.Miasto = pp.City;
pracownikDane.Adres = pp.Address;
pracownikDane.Telefon = pp.HomePhone;
pracownikDane.WWW = pp.PhotoPath;
}
return pracownikDane;
}
Right now you are just getting the .First() result from the Query collection:
Employee pp = query.First();
If you want to list all employees you need to iterate through the entire collection.
Now, if you want to return all the employee's you should then store each new "pracownikDane" you create in some sort of IEnumerable
public IEnumerable<PracownikDane> GetPracownik(string imie) {
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
var query = from pros in database.Employees
where pros.Title == imie
select pros;
var EmployeeList = new IEnumerable<PracownikDane>();
foreach(var pp in query)
{
EmployeeList.Add(new PracownikDane()
{
Tytul = pp.Title,
Imie = pp.FirstName,
Nazwisko = pp.LastName,
Kraj = pp.Country,
Miasto = pp.City,
Adres = pp.Address,
Telefon = pp.HomePhone,
WWW = pp.PhotoPath
});
}
return EmployeeList;
}
Then, with this returned List you can then do what ever you wanted with them.

Linq select fields

Just experimenting with Linq:
DataClassesDataContext db = new DataClassesDataContext();
var q = from p in db.tblBlogEntries select p;
foreach (var customer in q)
{
Response.Write(customer.ID + " " + customer.title + "\n");
}
Works fine, but I can only seem to return 1 field, or all of them. How do I select say, p.ID and p.title, and nothing else?
you need a projection to an anonymous type to only return the "parts" that you want:
var q = from p in db.tblBlogEntries select new { p.ID, p.Title };
Alternatively you could also define a new class that only has the subset of the properties you want. This might be beneficial if you want to return instances of the projection, since anonymous types can only be used in local scope:
var q = from p in db.tblBlogEntries
select new BlogTitleAndId() { ID = p.ID, Title = p.Title };
Instead of "select p"
Use:
var q = from p in db.tblBlogEntries select new { Column1 = p.Column1, Column2 = p.Column2 };
The new{} makes a inline class, so you can select whichever columns you need.
Something like this...
DataClassesDataContext db = new DataClassesDataContext();
var q = from p in db.tblBlogEntries select new { Id = p.ID, Title = p.title };
foreach (var customer in q)
{
Response.Write(customer.ID + " " + customer.title + "\n");
}
var q = from p in db.tblBlogEntries select new {p.ID, p.Title}
How about this:
DataClassesDataContext db = new DataClassesDataContext();
var q = from p in db.tblBlogEntries select new { ID = p.ID, title = p.title };
foreach (var customer in q)
{
Response.Write(customer.ID + " " + customer.title + "\n");
}
This part new { ID = p.ID, title = p.title } creates an anonymous class with members ID and title. You can add members for any column you wish and the types will be deduced automatically. Getting all the fields isn't that big a deal though. This article provides more information and a sample similar t yours.

ADO.NET Entity Framework Quirk

When I run the code below, it works
int charId = int.Parse(Request.Params["charId"]);
EveFPT ctx = new EveFPT();
var theCharQuery = from a in ctx.tblChars
where a.id == charId
select new
{
Name = a.name,
CorpName = a.tblCorps.name,
AllianceName = a.tblCorps.tblAlliances.name
};
if(theCharQuery.Count() == 1)
{
var theChar = theCharQuery.First();
lblCharName.Text = theChar.Name;
lblCorpName.Text = theChar.CorpName;
lblAllianceName.Text = theChar.AllianceName;
}
However, If I the below
var theCharQuery = from a in ctx.tblChars
where a.id == charId
select a;
if(theCharQuery.Count() == 1)
{
tblChars theChar = theCharQuery.First();
lblCharName.Text = theChar.name;
lblCorpName.Text = theChar.tblCorps.name;
lblAllianceName.Text = theChar.tblCorps.tblAlliances.name;
}
the statement
theChar.tblCorps
always returns null. Anyone know what's happening?
The Entity Framework doesn't eagerly load child object. You have to check if they're loaded, and then call Load() if they're not.
if(!theChar.tblCorps.IsLoaded)
{
theChar.tblCorps.Load();
}
Here's a good read from MSDN on the subject:
How to: Explicity Load Related Objects (Entity Framework)
I was thinking the same thing, although I wouldn't have expected it to eagerly load in the first example's projection expression either. Once way to try it:
var charId= int.Parse(Request.Params["charId"]);
EveFPT ctx = new EveFPT();
var theChar = ( from a in ctx.tblChars.Include ( "tblCorps" )
where a.id == charId
select new
{
Name = a.name,
CorpName = a.tblCorps.name,
AllianceName = a.tblCorps.tblAlliances.name
} ).FirstOrDefault ();
if(theChar != null)
{
lblCharName.Text = theChar.Name;
lblCorpName.Text = theChar.CorpName;
lblAllianceName.Text = theChar.AllianceName;
}

Categories