How to implement search functionality in C#/ASP.NET MVC - c#

I am developing an ASP.NET MVC 3 application using C# and Razor.
I have a search form that looks like this:
The search form works in the following way:
The user selects which property they want to search on.
The user selects how they want to match the search string (e.g. contains, starts with, ends with, equals, etc).
The user enters a search term and clicks Search.
The selections in the first drop down related directly to a property in my ADO.NET Entity Framework model class (and therefore directly to a table column).
Users need the ability to explicitly select which property and which matching method when searching, e.g. a user will explicitly search for all matches of process number that equals '132'.
My first approach was to use dynamic linq to construct a Where clause from the search criteria (see my original question). However I'm starting to think that this isn't the best way to do it.
I'm also hoping for a solution that doesn't require me to hard code the result for each property + matching criteria combination.
Any suggestions on how I should implement this search? It doesn't have to be using my current search form, totally open to any other ideas that fit the requirements.

Have you looked into using Lucene.NET for this project? given the nature of your searches it would be very simple to build that using Lucene, as it allows you to combine filters on different columns just like your requirements

You can build expression tree for where predicate using code. For example,
public static IQueryable<T> DynamicWhere<T>(this IQueryable<T> src, string propertyName, string value)
{
var pe = Expression.Parameter(typeof(T), "t");
var left = Expression.Property(pe, typeof(T).GetProperty(propertyName));
var right = Expression.Constant(value);
// Illustrated a equality condition but you can put a switch based on some parameter
// to have different operators
var condition = Expression.Equal(left, right);
var predicate = Expression.Lambda<Func<T, bool>>(condition, pe);
return src.Where(predicate);
}
Use it as Orders.DynamicWhere(searchBy, searchValue). You can add one more parameter to accept the operator such as Equals, Greater Than etc to complete the function.
See these links for more info:
http://msdn.microsoft.com/en-us/library/bb882637.aspx
http://msdn.microsoft.com/en-us/library/bb397951.aspx
Also check list of methods on the Expression class to get an idea.

You can use Dynamic Linq and you can create the Where clausole with a utility class like this:
public class Criteria
{
StringBuilder sb = new StringBuilder();
bool first = true;
public void And(string property, string dbOperator, string value) {
if (first)
{
sb.Append(" ").Append(property).Append(" ");
sb.Append(" ").Append(dbOperator).Append(" ");
sb.Append(" ").Append(value).Append(" ");
first = false;
}
else
{
sb.Append(" && ").Append(property).Append(" ");
sb.Append(" ").Append(dbOperator).Append(" ");
sb.Append(" ").Append(value).Append(" ");
}
}
public void Or(string property, string dbOperator, string value)
{
if (first)
{
sb.Append(" ").Append(property).Append(" ");
sb.Append(" ").Append(dbOperator).Append(" ");
sb.Append(" ").Append(value).Append(" ");
first = false;
}
else
{
sb.Append(" || ").Append(property).Append(" ");
sb.Append(" ").Append(dbOperator).Append(" ");
sb.Append(" ").Append(value).Append(" ");
}
}
public string ToString()
{
return sb.ToString();
}
}
So you can build a Criteria with many properties using Or or And methods and put it in the Where operator of Dynamic Linq.

We started out resolving similar queries against our Entity Framework model using dynamic linq queries. However, our attempts to generalize query generation resulted in bad performance due to EF being confused by the resulting complex expressions, so in the end horrible SQL was produced.
We resorted to Entity SQL.

Not sure if you are using MS SQL. Seems SQL could do most of the work for you, and you can build dynamic queries. Obviously the select/from statement needs work, but you can get the idea from the where clause.
DECLARE #SEARCHTYPE VARCHAR(20)
DECLARE #SEARCHTERM VARCHAR(100)
SELECT
[FIELDS]
FROM
[TABLE]
WHERE
(#SEARCHTYPE = 'BEGINSWITH' AND [FIELD] LIKE #SEARCHTERM + '%') OR
(#SEARCHTYPE = 'ENDSWITH' AND [FIELD] LIKE '%' + #SEARCHTERM) OR
(#SEARCHTYPE = 'EQUALS' AND [FIELD] = #SEARCHTERM)

You could have the first combo data source set to myEntityObject.GetType().GetProperties(), the second to a list of displayable Funcs<string, string, bool>, like this:
public class ComboPredicate
{
public Func<string, string, bool> Func {get; set;}
public string Name {get; set; }
}
Later, when you load the form:
comboProperty.Datasource = myEntityObject.GetType().GetProperties()
comboOperation.Datasource = new List<Predicate>
{
{
Name = "Contains",
Predicate = (s1, s2) => s1 != null && s1.Contains(s2),
},
{
Name = "Equals",
Predicate = (s1, s2) => string.Compare(s1, s2) == 0,
},
//...
}
And later, when you want to select your entities:
var propertyInfo = (PropertyInfo)comboProperty.SelectedValue;
var predicate = ((ComboPredicate)comboOperation.SelectedValue).Predicate;
var filteredObjects = objects.Where(o => predicate(propertyInfo.GetValue(o, null).ToString(), textBoxValue.Text));

create method and call it on button click demo below
public List gettaskssdata(int c, int userid, string a, string StartDate, string EndDate, string ProjectID, string statusid)
{
List<tbltask> tbtask = new List<tbltask>();
var selectproject = entity.tbluserprojects.Where(x => x.user_id == userid).Select(x => x.Projectid);
if (statusid != "" && ProjectID != "" && a != "" && StartDate != "" && EndDate != "")
{
int pid = Convert.ToInt32(ProjectID);
int sid = Convert.ToInt32(statusid);
DateTime sdate = Convert.ToDateTime(StartDate).Date;
DateTime edate = Convert.ToDateTime(EndDate).Date;
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblproject.ProjectId == pid) && (x.tblstatu.StatusId == sid) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)) && (x.StartDate >= sdate && x.EndDate <= edate)).OrderByDescending(x => x.ProjectId).ToList();
}
else if (statusid == "" && ProjectID != "" && a != "" && StartDate != "" && EndDate != "")
{
int pid = Convert.ToInt32(ProjectID);
DateTime sdate = Convert.ToDateTime(StartDate).Date;
DateTime edate = Convert.ToDateTime(EndDate).Date;
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblproject.ProjectId == pid) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)) && (x.StartDate >= sdate && x.EndDate <= edate)).OrderByDescending(x => x.ProjectId).ToList();
}
else if (ProjectID == "" && statusid != "" && a != "" && StartDate != "" && EndDate != "")
{
int sid = Convert.ToInt32(statusid);
DateTime sdate = Convert.ToDateTime(StartDate).Date;
DateTime edate = Convert.ToDateTime(EndDate).Date;
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblstatu.StatusId == sid) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)) && (x.StartDate >= sdate && x.EndDate <= edate)).OrderByDescending(x => x.ProjectId).ToList();
}
else if(ProjectID!="" && StartDate == "" && EndDate == "" && statusid == "" && a == "")
{
int pid = Convert.ToInt32(ProjectID);
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblproject.ProjectId == pid)).OrderByDescending(x => x.ProjectId).ToList();
}
else if(statusid!="" && ProjectID=="" && StartDate == "" && EndDate == "" && a == "")
{
int sid = Convert.ToInt32(statusid);
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblstatu.StatusId == sid) ).OrderByDescending(x => x.ProjectId).ToList();
}
else if (a == "" && StartDate != "" && EndDate != "" && ProjectID != "")
{
int pid = Convert.ToInt32(ProjectID);
DateTime sdate = Convert.ToDateTime(StartDate).Date;
DateTime edate = Convert.ToDateTime(EndDate).Date;
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.ProjectId == pid) && (x.StartDate >= sdate && x.EndDate <= edate)).OrderByDescending(x => x.ProjectId).ToList();
}
else if (StartDate == "" && EndDate == "" && statusid != "" && ProjectID != "" && a != "")
{
int pid = Convert.ToInt32(ProjectID);
int sid = Convert.ToInt32(statusid);
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblproject.ProjectId == pid) && (x.tblstatu.StatusId == sid) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a))).OrderByDescending(x => x.ProjectId).ToList();
}
else if (a == "" && StartDate == "" && EndDate == "" && ProjectID != "" && statusid != "")
{
int pid = Convert.ToInt32(ProjectID);
int sid = Convert.ToInt32(statusid);
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Include(x => x.tblstatu).Where(x => selectproject.Contains(x.ProjectId) && x.tblproject.company_id == c && x.tblproject.ProjectId == pid && x.tblstatu.StatusId == sid).OrderByDescending(x => x.ProjectId).ToList();
}
else if (a != "" && StartDate == "" && EndDate == "" && ProjectID == "" && statusid == "")
{
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a))).OrderByDescending(x => x.ProjectId).ToList();
}
else if (a != "" && ProjectID != "" && StartDate == "" && EndDate == "" && statusid == "")
{
int pid = Convert.ToInt32(ProjectID);
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.tblproject.ProjectId == pid) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a))).OrderByDescending(x => x.ProjectId).ToList();
}
else if (a != "" && StartDate != "" && EndDate != "" && ProjectID == "" && statusid == "")
{
DateTime sdate = Convert.ToDateTime(StartDate).Date;
DateTime edate = Convert.ToDateTime(EndDate).Date;
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && (x.tblproject.company_id == c) && (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)) && (x.StartDate >= sdate && x.EndDate <= edate)).OrderByDescending(x => x.ProjectId).ToList();
}
else
{
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).Where(x => selectproject.Contains(x.ProjectId) && x.tblproject.company_id == c).OrderByDescending(x => x.ProjectId).ToList();
}
return tbtask;
}

Related

The cast to value type System.Boolean failed because the materialized value is null, result type's generic parameter must use a nullable type

This code was working before but now I've got this error: The cast to value type 'System.Boolean' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
public async Task<ActionResult> BankDepositVoucher(BankDepositVoucherSearchViewModel search, int? PageNo)
{
var model = new BankDepositVoucherListViewModel
{
Search = search ?? new BankDepositVoucherSearchViewModel()
};
if (search != null)
{
search.StartDate = search.StartDate.ToStartOfDay();
search.EndDate = search.EndDate.ToEndOfDay();
}
try
{
var Vouchers = DbManager.Invoices.Include(x => x.BankDepositVoucher)
.Where(x => x.Type == InvoiceType.BankDepositVoucher
&& (x.VoucherNumber == search.VoucherNo || search.VoucherNo == null)
&& (x.BankDepositVoucher.SlipNo.Contains(search.SlipNo) || search.SlipNo == null)
&& (x.BankDepositVoucher.ChequeNo.Contains(search.ChequeNo) || search.ChequeNo == null)
&& (x.BankDepositVoucher.Bank.AccountName.Contains(search.BankDetails)
|| search.BankDetails == null)
&& (x.BankDepositVoucher.AccountName.Contains(search.AccountName) || search.AccountName == null)
&& (x.BankDepositVoucher.Narration.Contains(search.Narration) || search.Narration == null)
&& (x.TotalAmount == search.Amount || search.Amount == null)
&& (x.Date >= search.StartDate || search.StartDate == null)
&& (x.Date <= search.EndDate || search.EndDate == null));
//model.Pager = new Pager(await Vouchers.CountAsync(), PageNo, 10);
model.Vouchers = await Vouchers.OrderByDescending(x => x.VoucherNumber)
//.Skip((model.Pager.CurrentPage - 1) * model.Pager.PageSize)
//.Take(model.Pager.PageSize)
.Select(x => new BankDepositVoucherBaseViewModel
{
Id = x.Id,
VoucherNumber = x.VoucherNumber,
AccountName = x.BankDepositVoucher.AccountName,
BankAccountName = x.BankDepositVoucher.Bank.AccountName,
Date = x.Date,
ChequeNo = x.BankDepositVoucher.ChequeNo,
Narration = x.BankDepositVoucher.Narration,
SlipNo = x.BankDepositVoucher.SlipNo,
TotalAmount = x.TotalAmount,
IsCleared = x.BankDepositVoucher.IsCleared
}).ToListAsync();
}
catch (Exception ex)
{
Console.WriteLine("", ex.Message);
}
return PartialView(model);
}
This is the part throwing above mentioned exception
model.Vouchers = await Vouchers.OrderByDescending(x => x.VoucherNumber)
//.Skip((model.Pager.CurrentPage - 1) * model.Pager.PageSize)
//.Take(model.Pager.PageSize)
.Select(x => new BankDepositVoucherBaseViewModel
{
Id = x.Id,
VoucherNumber = x.VoucherNumber,
AccountName = x.BankDepositVoucher.AccountName,
BankAccountName = x.BankDepositVoucher.Bank.AccountName,
Date = x.Date,
ChequeNo = x.BankDepositVoucher.ChequeNo,
Narration = x.BankDepositVoucher.Narration,
SlipNo = x.BankDepositVoucher.SlipNo,
TotalAmount = x.TotalAmount,
IsCleared = x.BankDepositVoucher.IsCleared
}).ToListAsync();
The issue is likely that when populating the view model it cannot deal with the fact that a record may not have a BankDepositVoucher.
For instance:
IsCleared = x.BankDepositVoucher.IsCleared
This should probably be:
IsCleared = x.BankDepositVoucher?.IsCleared ?? false
One other thing to improve performance considerably:
While it may look concise in the code to write statements like this:
.Where(x => x.Type == InvoiceType.BankDepositVoucher
&& (x.VoucherNumber == search.VoucherNo || search.VoucherNo == null)
&& (x.BankDepositVoucher.SlipNo.Contains(search.SlipNo) || search.SlipNo == null)
&& (x.BankDepositVoucher.ChequeNo.Contains(search.ChequeNo) || search.ChequeNo == null)
&& (x.BankDepositVoucher.Bank.AccountName.Contains(search.BankDetails)
|| search.BankDetails == null)
&& (x.BankDepositVoucher.AccountName.Contains(search.AccountName) || search.AccountName == null)
&& (x.BankDepositVoucher.Narration.Contains(search.Narration) || search.Narration == null)
&& (x.TotalAmount == search.Amount || search.Amount == null)
&& (x.Date >= search.StartDate || search.StartDate == null)
&& (x.Date <= search.EndDate || search.EndDate == null));
It is more efficient to write it out as:
.Where(x => x.Type == InvoiceType.BankDepositVoucher);
if(!string.IsNullOrEmpty(search.VoucherNo))
Voucher = Voucher.Where(x => x.VoucherNumber == search.VoucherNo);
if(!string.IsNullOrEmpty(search.SlipNo))
Voucher = Voucher.Where(x => x.BankDepositVoucher.SlipNo.Contains(search.SlipNo))
// etc.
The reason is that in the first case you are generating a much larger SQL statement to be sent to the database, and it is quite easy to "slip up" on conditions if that query is ever edited in the future. (missing parenthesis, etc.) The second example only adds conditions to the query if they are needed, keeping the resulting SQL statement much more compact.

IQueryable with only optional parameters

I currently have the following method:
public List<Order> GetOrders(int profileId, string timeSpan, string workOrd, string partNo, bool includeDeleted)
{
DateTime startDate = DateTime.Now;
DateTime endDate = DateTime.Now;
string[] times = (!string.IsNullOrWhiteSpace(timeSpan)) ? timeSpan.Trim().Split('-') : new string[] { "", "" };
if (!string.IsNullOrWhiteSpace(times[0]) && !string.IsNullOrWhiteSpace(times[0]))
{
startDate = DateTime.Parse(times[0]).Date;
endDate = DateTime.Parse(times[1]).Date;
}
//New Real Query
IQueryable<Order_Travel> otQuery = _context.Order_Travels.Where(x =>
(profileId != 0 || x.Profile.ProfileID == profileId)
&& ((timeSpan == null || timeSpan.Trim() == "") || ((DbFunctions.TruncateTime(x.TimeRecieved) >= startDate)
&& (DbFunctions.TruncateTime(x.TimeRecieved) <= endDate)))
&& ((workOrd == null || workOrd.Trim() == "") || x.Order.WorkOrdNo == workOrd)
&& ((partNo == null ||partNo.Trim() == "") || x.Order.PartNo == partNo)
&& (!includeDeleted || x.Aborted == true));
//The results is now in order_travel. Under here binding them to a list of orders with only the respective orderTravels included.
List<Order> orders = new List<Order>();
List<Order_Travel> ots = otQuery.ToList();
foreach (Order_Travel ot in ots)
{
var OrderInList = orders.FirstOrDefault(X => X == ot.Order);
if (OrderInList == null)
{
orders.Add(ot.Order);
OrderInList = orders.FirstOrDefault(X => X == ot.Order);
OrderInList.OrderTravels.Clear();
OrderInList.OrderTravels.Add(ot);
}
else
{
OrderInList.OrderTravels.Add(ot);
}
}
return orders;
}
What I need it to do, is (as I've attempted) to make a call, finding all Order_Travel objects that match the paramters sent to it. If some (or all) are left blank, it takes everything, regardless of the values.
The code right now, does not return anything, if a blank search is made (a search that does not have any parameters), and I can not see what could be the issue. I have tried debugging it, but with no luck.
Any help would be greatly appreciated!
Thanks!
Filter one option at a time, instead of trying to put everything into a single expression:
IQueryable<T> query = all; // start with everything
if (IsPresent(option1))
{
query = query.Where(t => t.XXX == option1);
}
Example
IQueryable<Order_Travel> otQuery = _context.Order_Travels;
if (profileId != 0)
{
otQuery = otQuery.Where(x => x.Profile.ProfileID == profileId);
}
if (timeSpan != null && timeSpan.Trim() != "")
{
otQuery = otQuery.Where(x => DbFunctions.TruncateTime(x.TimeRecieved) >= startDate &&
DbFunctions.TruncateTime(x.TimeRecieved) <= endDate);
}
You will also find this easier to maintain than one huge expression.
Probably this part is your problem:
(profileId != 0 || x.Profile.ProfileID == profileId)
It should be
(profileId == 0 || x.Profile.ProfileID == profileId)
If your profile ID is 0, it will only find entries with x.Profile.ProfileID being 0. Probably there are no such entries.

randomize Select do not work

I wrote a code that's going to accidentally bring back row of data
I want to 5 row chosen randomly but do not work and return value
Everything was true, but the part that is related to the random return just do not work anymore
public List<tblInvoice> Admin_GetRowsSendProduct(string StartDate, string EndDate, int status = -1, bool Randomize = false)
{
LtSProductDataContext db = new LtSProductDataContext(BLLBase.BLLBase.ConnectionString);
IQueryable<tblInvoice> xxx = db.tblInvoices.Where(p => p.status == true);
DateTime _StartDate = DateTime.MinValue;
DateTime _EndDate = DateTime.MinValue;
if (xConvertor.ToString(StartDate) == "" || xConvertor.ToString(EndDate) == "")
{
if (string.IsNullOrEmpty(StartDate) == false)
_StartDate = BLLBase.xDateTime.DateXorshid2DateMiladi(StartDate.ToString());
if (string.IsNullOrEmpty(EndDate) == false)
{
_EndDate = BLLBase.xDateTime.DateXorshid2DateMiladi(EndDate.ToString());
if (_StartDate == _EndDate) { _EndDate = _StartDate.AddDays(1); }
}
xxx = xxx.Where(p =>
(p.status == true) &&
(_StartDate == DateTime.MinValue || p.Date >= _StartDate) && (_EndDate == DateTime.MinValue || p.Date <= _EndDate));
}
else if (xConvertor.ToString(StartDate) != "" && xConvertor.ToString(EndDate) != "")
{
_StartDate = BLLBase.xDateTime.DateXorshid2DateMiladi(StartDate.ToString());
_EndDate = BLLBase.xDateTime.DateXorshid2DateMiladi(EndDate.ToString());
xxx = xxx.Where(p => p.Date <= _EndDate && p.Date >= _StartDate && p.status == true && p.SendStatus == status);
}
xxx = xxx.Where(p => (status == -1 || p.SendStatus == status) && p.status == true).OrderByDescending(p => p.Date);
if (Randomize)
{
Random rnd = new Random();
xxx = xxx.OrderBy(x => rnd.Next());
//xxx = xxx.OrderBy(o => Guid.NewGuid());
xxx = xxx.Take(3);
return xxx.Where(p => (p.isPostalPayment == null || p.isPostalPayment == false)).ToList();
}
else
{
return xxx.Where(p => (p.isPostalPayment == null || p.isPostalPayment == false)).ToList();
}
//return xxx.Where(p => p.PaymentType != 4).ToList();
}
do not work this section:
xxx = xxx.OrderBy(x => rnd.Next());
or
xxx = xxx.OrderBy(o => Guid.NewGuid());
if (Randomize)
{
List<tblInvoice> _Result = db.tblInvoices.ToList();
var _Temp = xxx.Where(p => (p.isPostalPayment == null || p.isPostalPayment == false)).ToList();
_Result = _Temp.OrderBy(o => Guid.NewGuid()).Take(5).ToList();
return _Result;
}

Include where clause on linq query when param is not null Npgsql

I have following method that registers a contact in database, but before register I check the contact exists or not:
bool RegisterContact(Contact contactInfo) {
bool entityExists =
_dbContext.Contacts.FirstOrDefault(
p => (p.FilesID.Equals(contactInfo.FilesID))
&& (p.EmailAddress ==
(string.IsNullOrEmpty(
contactInfo.EmailAddress)
? p.EmailAddress
: contactInfo.EmailAddress))
&&
(p.DisplayName ==
(string.IsNullOrEmpty(
contactInfo.DisplayName)
? p.DisplayName
: contactInfo.DisplayName)));
}
this query includes the fields that contain value (not null) in search condition (FilesID, EmailAddress, DisplayName)
this technique works fine in MSSQL, today i changed the database manager to PostgreSQL and use Npgsql.
All things work except above linq query, which raises an exception with message of : "could not determine data type of parameter $2"
I was forced to solve it in this way:
bool RegisterContact(Contact contactInfo)
{
Contact entityExists = null;
if (string.IsNullOrEmpty(contactInfo.EmailAddress) &&
(string.IsNullOrEmpty(contactInfo.DisplayName)))
entityExists =
_dbContext.Contacts.FirstOrDefault(
p => p.FilesID.Equals(contactInfo.FilesID));
if (!string.IsNullOrEmpty(contactInfo.EmailAddress) && string.IsNullOrEmpty(contactInfo.DisplayName))
entityExists =
_dbContext.Contacts.FirstOrDefault(
p =>
p.FilesID.Equals(contactInfo.FilesID) &&
p.EmailAddress == contactInfo.EmailAddress);
if (string.IsNullOrEmpty(contactInfo.EmailAddress) && !string.IsNullOrEmpty(contactInfo.DisplayName))
entityExists =
_dbContext.Contacts.FirstOrDefault(
p =>
p.FilesID.Equals(contactInfo.FilesID) &&
p.DisplayName == contactInfo.DisplayName);
if (!string.IsNullOrEmpty(contactInfo.EmailAddress) &&
!string.IsNullOrEmpty(contactInfo.DisplayName))
entityExists =
_dbContext.Contacts.FirstOrDefault(
p =>
p.FilesID.Equals(contactInfo.FilesID) &&
p.EmailAddress == contactInfo.EmailAddress &&
p.DisplayName == contactInfo.DisplayName);
}
Is this Npgsql bug or by design? any known solutions/workarounds for the problem?
I currently have the same cases. I think the problem is the lack of recognition, by NpgSQL, of string.IsNullOrEmpty.
I replaced the test with a check on empty string, always recognizing as not NULL the input parameter.
-- bad
var data = from art in _ctx.Set<Soleo.Model.DLAR>()
from iva in _ctx.Set<Soleo.Model.DLAI>().Where(k => k.DITTA == art.DITTA && k.COD == art.CIVA).DefaultIfEmpty()
from fam in _ctx.Set<Soleo.Model.DLFA>().Where(k => k.DITTA == art.DITTA && k.COD == art.FAM).DefaultIfEmpty()
from mar in _ctx.Set<Soleo.Model.DLMA>().Where(k => k.DITTA == art.DITTA && k.COD == art.MAR).DefaultIfEmpty()
from udm in _ctx.Set<Soleo.Model.DLUM>().Where(k => k.DITTA == art.DITTA && k.COD == art.UM).DefaultIfEmpty()
where art.DITTA == DLAUTH.Config.Current.DITTA && art.COD.Contains(sel_cod) && art.DES.Contains(sel_des)
&& (string.IsNullOrEmpty(sel_fam) || string.Compare(art.FAM, sel_fam, true) == 0)
&& (string.IsNullOrEmpty(sel_mar) || string.Compare(art.MAR, sel_mar, true) == 0)
&& (art.DIS >= sel_dis_da && art.DIS <= sel_dis_a)
select new
{
COD = art.COD,
DES = art.DES,
DES_UDM = udm.DES,
DES_MAR = mar.DES,
DES_FAM = fam.DES,
DES_CIVA = iva.DES,
MAG1 = art.MAG1,
MAG2 = art.MAG2,
DES_DIS = art.DIS == 1 ? "Si" : "No"
};
-- good:
var data = from art in _ctx.Set<Soleo.Model.DLAR>()
from iva in _ctx.Set<Soleo.Model.DLAI>().Where(k => k.DITTA == art.DITTA && k.COD == art.CIVA).DefaultIfEmpty()
from fam in _ctx.Set<Soleo.Model.DLFA>().Where(k => k.DITTA == art.DITTA && k.COD == art.FAM).DefaultIfEmpty()
from mar in _ctx.Set<Soleo.Model.DLMA>().Where(k => k.DITTA == art.DITTA && k.COD == art.MAR).DefaultIfEmpty()
from udm in _ctx.Set<Soleo.Model.DLUM>().Where(k => k.DITTA == art.DITTA && k.COD == art.UM).DefaultIfEmpty()
where art.DITTA == DLAUTH.Config.Current.DITTA && art.COD.Contains(sel_cod) && art.DES.Contains(sel_des)
&& (string.Compare(sel_fam, "", true) == 0 || string.Compare(art.FAM, sel_fam, true) == 0)
&& (string.Compare(sel_mar, "", true) == 0 || string.Compare(art.MAR, sel_mar, true) == 0)
&& (art.DIS >= sel_dis_da && art.DIS <= sel_dis_a)
select new
{
COD = art.COD,
DES = art.DES,
DES_UDM = udm.DES,
DES_MAR = mar.DES,
DES_FAM = fam.DES,
DES_CIVA = iva.DES,
MAG1 = art.MAG1,
MAG2 = art.MAG2,
DES_DIS = art.DIS == 1 ? "Si" : "No"
};
But I do not think this is the solution. I will report the case to NpgSQL.

Return all in List <T> in lambda expression

I'm using lambda expression in LINQ where i have to get all the result when the conditon satisfies if not it should filter.
//Code
List<Dispatch> objDispatch = (List<Dispatch>)Session["Data"];
objDispatch = objDispatch.FindAll(dispatch => dispatch.CustomerTransName == ddlTransporterName.SelectedItem.Text && dispatch.InvoiceDate.Date >= Convert.ToDateTime(FromDate).Date && dispatch.InvoiceDate.Date <= Convert.ToDateTime(ToDate).Date);
In the above code i'm filtering the result set with some conditions in that first condition i need a help.
If the transporter name is 'ALL' it should return all the result set it matches with the Date condition or else it should return according to the TransporterName.
How can i achieve this?
With pure logic.
if(ddlTransporterName.SelectedItem.Text == "ALL") {
//return all
} else {
//Do your filter logic
}
Or, with less repitive code:
objDispatch = objDispatch.FindAll(
dispatch => (ddlTransporterName.SelectedItem.Text == "ALL" || dispatch.CustomerTransName == ddlTransporterName.SelectedItem.Text)
&& dispatch.InvoiceDate.Date >= Convert.ToDateTime(FromDate).Date
&& dispatch.InvoiceDate.Date <= Convert.ToDateTime(ToDate).Date);
string name = ddlTransporterName.SelectedItem.Text;
objDispatch = objDispatch.FindAll(dispatch =>
(name == "ALL" || dispatch.CustomerTransName == name)
&& dispatch.InvoiceDate.Date >= Convert.ToDateTime(FromDate).Date
&& dispatch.InvoiceDate.Date <= Convert.ToDateTime(ToDate).Date);
If transporter name is "ALL" then name OR condition will give true and CustomerTransName will not be checked.
If you want this to be LINQ then you need to actually use a LINQ method e.g. use Where. Also you should do your date conversions once outside if they aren't specific to the row, otherwise they will be converting everytime. Not only that, it makes for more readable code...
var selectedTransporter = ddlTransporterName.SelectedItem.Text;
var fromDate = Convert.ToDateTime(FromDate).Date;
var toDate = Convert.ToDateTime(ToDate).Date;
var query = objDispatch.Where(x => (selectedTransporter == "All" || x.CustomerTransName == selectedTransporter) && x.InvoiceDate.Date >= fromDate && x.InvoiceDate.Date <= toDate);
I think this should suffice:
List<Dispatch> objDispatch = (List<Dispatch>)Session["Data"];
List<Dispatch> filteredDispatches = objDispatch.Where(dispatch => dispatch.InvoiceDate.Date >= Convert.ToDateTime(FromDate).Date && dispatch.InvoiceDate.Date <= Convert.ToDateTime(ToDate).Date).ToList();
if (ddlTransporterName.SelectedItem.Text != "ALL")
{
filteredDispatches = filteredDispatches.Where(dispatch => dispatch.CustomerTransName == ddlTransporterName.SelectedItem.Text).ToList();
}
I think something like this should work:
List<Dispatch> objDispatch = (List<Dispatch>)Session["Data"];
var _fromDate = Convert.ToDateTime(FromDate);
var _toDate = Convert.ToDateTime(ToDate);
objDispatch = objDispatch
.FindAll(dispatch => Selector(
dispatch, ddlTransporterName.SelectedItem.Text, _fromDate, _toDate));
static bool Selector(
Dispatch dispatch, string name, DateTime fromDate, DateTime toDate)
{
if (dispatch.CustomerTransName == "ALL")
{
return dispatch.InvoiceDate.Date >= fromDate.Date
&& dispatch.InvoiceDate.Date <= toDate.Date;
}
return dispatch.CustomerTransName == name;
}

Categories

Resources