Case Statements in LINQ query - AnonymousType to String? - asp.net

I basically have the following:
public ActionResult Search(string searchString, string clientNo, int status = -1)
{
var statusLst = new List<string>();
var statusNoQry = from b in db.Briefs
orderby b.Status
select new
{
status = (
b.Status == 0 ? "Requested" :
b.Status == 1 ? "In Progress" :
"Undefined"
)
};
statusLst.AddRange(statusNoQry.Distinct()); <<--- ERROR HERE
ViewBag.status = new SelectList(statusLst);
var ClientNoLst = new List<string>();
var ClientNoQry = from b in db.Briefs
orderby b.Client_No_
where b.Client_Type == 0
select b.Client_No_;
ClientNoLst.AddRange(ClientNoQry.Distinct());
ViewBag.clientNo = new SelectList(ClientNoLst);
var briefs = from b in db.Briefs
select b;
Session["searchString"] = searchString;
Session["clientNo"] = clientNo;
if (!String.IsNullOrEmpty(searchString))
{
briefs = briefs.Where(s => s.Client_No_.Contains(searchString) || s.Name.Contains(searchString));
}
if ((status > -1) && (status < 10))
{
briefs = briefs.Where(y => y.Status == status);
}
if (string.IsNullOrEmpty(clientNo))
return View(briefs);
else
return View(briefs.Where(x => x.Client_No_ == clientNo));
}
However, I receive the following area:
Error 7 Argument 1: cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<string>'
Status is of type int but I would like to cast it to string for my dropdownlist. I'm quite new to all this, what is the appropriate way of achieving this?

Your selector is returning an anonymous type:
select new
{
status = (
b.Status == 0 ? "Requested" :
b.Status == 1 ? "In Progress" :
"Undefined"
)
};
You need to return a set of strings though. The error is telling you exactly what the problem is.
select
(b.Status == 0 ? "Requested" :
b.Status == 1 ? "In Progress" :
"Undefined");
Edit - You didn't post the rest of the method, but from you have your also not disposing your context object, which can cause problems. Normally you wrap this in a using clause.

Related

Pagination on DevExtreme dxDataGrid with Skip / Take loadOptions

We have a table with a large amount of data and I do not want to load it at once for my dxDataGrid.
I want to implement paging with Skip / Take which is supplied from the dxDataGrid's DataSourceLoadOptions.
This is my controller:
[HttpGet]
public async Task<Object> GetSalesOrdersWithTotals(DataSourceLoadOptions loadOptions)
{
try
{
var results = await SalesOrderService.GetSalesOrdersWithTotals(loadOptions.Skip, loadOptions.Take, 40);
loadOptions.Skip = 0;
loadOptions.Take = 0;
return DataSourceLoader.Load(results, loadOptions);
}
catch (Exception ex)
{
return Json(new { code = "422", success = false, message = "Unable to fetch sales orders with totals - " + ex.ToString() });
}
}
This is the service that returns the data:
public async Task<IEnumerable<SalesOrderWithTotals>> GetSalesOrdersWithTotals(int skip, int take, int defaultPageSize)
{
if (take == 0)
{
//Fix for passing a 0 take
take = defaultPageSize;
}
var salesOrderWithTotals =
from o in _context.SalesOrder
select new SalesOrderWithTotals
{
SalesOrderId = o.SalesOrderId,
Net = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum(),
Tax = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() * (o.Tax.Percentage /100),
Gross = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() + _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() * (o.Tax.Percentage / 100),
Name = o.Customer.Name,
CustomerOrderNumber = o.CustomerOrderNumber,
Contact = o.Contact,
OrderDate = o.OrderDate
};
return await salesOrderWithTotals.Skip(skip).Take(take).ToListAsync();
}
Looking at SQL profiler, this takes the first 40 records but of course the dxDataGrid is not aware of the total count of records so pagination is not available.
What would be the best method to achieve what I want in this case?
Many thanks
You must do an extra query to get the count of your SalesOrder and keep it in for example salesOrderCount. Then keep the Load method return data as bellow.
LoadResult result = DataSourceLoader.Load(results, loadOptions);
LoadResult has a parameter called totalCount so set it with the real count of your data:
result.totalCount = salesOrderCount;
and then
return result;
Now the dxDataGrid is aware of the total count of records.

Datatables Object Reference not set to instance of an object for one variable

This is my datatables serverside implementation. FilterInput contains 5 variables:
Level <- string
Message <- string
Exception <-string
StartDate <- DateTime
EndDate <- DateTime
For some reason when I run this code as it is, I will always get this error:
{System.NullReferenceException: Object reference not set to an
instance of an object.
This is referring to this line:
data = data.Where(
u => u.Level.ToString().ToLower().Contains(FilterInput.Level.ToLower()) &&
u.Message.ToString().ToLower().Contains(FilterInput.Message.ToLower()) &&
u.Exception.ToString().ToLower().Contains(FilterInput.Exception.ToLower())
).ToList();
However, if I remove the search for FilterInput.Exception, everything runs fine again. I have tested it with input ("abc") or without input ("") and the results are the same. The other FilterInputs don't have the same error.
public JsonResult Search(SearchViewModels Input, EventLogsSearchViewModel FilterInput)
{
JsonResult result = new JsonResult(null);
try
{
var data = dbContext.EventLogs.ToList();
int totalRecords = data.Count;
var modelStructure = new Dictionary<int, string>();
modelStructure.Add(1, "Level");
modelStructure.Add(2, "TimeStamp");
modelStructure.Add(3, "LogEvent");
modelStructure.Add(4, "Message");
modelStructure.Add(5, "MessageTemplate");
modelStructure.Add(6, "Exception");
modelStructure.Add(7, "Properties");
var StartDate = FilterInput.StartDate != default(DateTime);
var EndDate = FilterInput.EndDate != default(DateTime);
if ((!string.IsNullOrEmpty(FilterInput.Level) && !string.IsNullOrWhiteSpace(FilterInput.Level)) ||
(!string.IsNullOrEmpty(FilterInput.Message) && !string.IsNullOrWhiteSpace(FilterInput.Message)) ||
(!string.IsNullOrEmpty(FilterInput.Exception) && !string.IsNullOrWhiteSpace(FilterInput.Exception)) ||
(StartDate && EndDate))
{
data = data.Where(
u => u.Level.ToString().ToLower().Contains(FilterInput.Level.ToLower()) &&
u.Message.ToString().ToLower().Contains(FilterInput.Message.ToLower()) &&
u.Exception.ToString().ToLower().Contains(FilterInput.Exception.ToLower())
).ToList();
data = data.Where(u => u.TimeStamp >= FilterInput.StartDate && u.TimeStamp <= FilterInput.EndDate).ToList();
}
if (!(string.IsNullOrEmpty(Input.Order) && string.IsNullOrEmpty(Input.OrderDir)))
{
var columnName = modelStructure.FirstOrDefault(f => f.Key == Convert.ToInt32(Input.Order));
data = data.AsQueryable().OrderBy(columnName.Value + " " + Input.OrderDir).ToList();
}
int recFilter = data.Count;
data = data.Skip(Input.StartRec).Take(Input.PageSize).ToList();
var modifiedData = data.Select(u => new EventLogsListViewModel
{
Id = u.Id,
Message = u.Message,
MessageTemplate = u.MessageTemplate,
Level = u.Level,
TimeStamp = u.TimeStamp,
Exception = u.Exception,
Properties = u.Properties,
LogEvent = u.LogEvent
});
result = this.Json(new
{
draw = Convert.ToInt32(Input.Draw),
recordsTotal = totalRecords,
recordsFiltered = recFilter,
data = modifiedData,
order = Input.Order,
orderdir = Input.OrderDir
});
}
catch (Exception e)
{
logger.LogError(e, LoggingGlobals.LoadingException);
}
return result;
}
EDIT: The exception still happens even when FilterInput.Exception is not null

The best overloaded method match for int tryparse Error

I'm simply trying to do this, so later on when I save my values in the database they should be set to null incase the textfield is empty.
int? DeliveryAdrID = null;
int.TryParse(TextBoxDeliveryAdrID.Text, out DeliveryAdrID);
But I'm having an error parsing it along.
The above solution should later on make it possible to save empty textbox values in the database as "NULL" instead of 0.
The whole solution:
int parsedValue;
int? DeliveryAdrID = int.TryParse(TextBoxDeliveryAdrID.Text, out parsedValue) ? parsedValue : (int?)null;
int id = Convert.ToInt32(GridViewData.SelectedValue.ToString());
var data = tf.DBTable.Where(a => a.ID == id).FirstOrDefault();
if (data == null)
{
DBTable mt = new DBTable();
mt.Customer = TextBoxCustomer.Text;
mt.Country = TextBoxCountry.Text;
mt.DeliveryAdrID = parsedValue;
tf.DBTable.AddObject(mt);
tf.SaveChanges();
}
else
{
data.Customer = TextBoxCustomer.Text;
data.Country = TextBoxCountry.Text;
data.DeliveryAdrID = parsedValue;
tf.SaveChanges();
}
}
You cannot give a nullable int to int.TryParse. It must be an int. What you are trying to do can be accomplished like so:
int parsedValue;
int? DeliveryAdrID = int.TryParse(TextBoxDeliveryAdrID.Text, out parsedValue) ? parsedValue : (int?) null;

Trying to get Distinct() and/or GroupBy(...) in returned ToList

The code is working and returning a good list with (6) items.
However, we are seeing duplicates productSKU. We want to do a
DISTINCt productSKU.
pM = (from oo in ctx.option1
where mArray.Contains(oo.option1Code)
select oo)
.Select(o => new ProductMatch
{
productSKU = o.option1Code,
productPrice = o.price,
option1Desc = o.option1Desc
}).ToList();
I have tried to add Distinct() after the Lambda but I still get (6) items.
I am also getting error when I add GroupBy(...) "Cannot convert lambda expression to type 'string' because it is not a delegate type"
Try this syntax:
pM = (from o in ctx.option1
where mArray.Contains(o.option1Code)
let t = new
{
productSKU = o.option1Code,
productPrice = o.price,
option1Desc = o.option1Desc
}
group o by t into grp
select new ProductMatch
{
productSKU = grp.Key.option1Code,
productPrice = grp.Key.price,
option1Desc = grp.Key.option1Desc
}).ToList();
When you use a Distinct on a lamba expression, the Distinct only looks at the EntityKey for the distinct comparision. You will need to implement your own IEqualityComparer for your select.
internal class UniqueProductComparer : IEqualityComparer<ProductMatch>
{
public bool Equals(ProductMatch x, ProductMatch y)
{
if(Object.ReferenceEquals(x,y)) return true;
if(Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y,null))
return false;
return x.productSKU == y.ProductSKU && x.productPrice == y.productPrice && x.option1Desc == y.option1Desc;
}
public int GetHashCode(ProductMatch match)
{
if (Object.ReferenceEquals(match,null)) return 0;
return match.productSKU.GetHashChode() + match.productPrice.GetHashCode() + match.option1Desc.GetHashCode();
}
}
Then in your lamba, change it to this:
pM = (from oo in ctx.option1
where mArray.Contains(oo.option1Code)
select oo)
.Select(o => new ProductMatch
{
productSKU = o.option1Code,
productPrice = o.price,
option1Desc = o.option1Desc
}).Distinct(new UniqueProductComparer()).ToList();
A slight variation of IAbstractDownvoteFactor's answer
pM = (from oo in ctx.option1
where mArray.Contains(oo.option1Code)
select oo)
.GroupBy(o => o.option1Code)
.Select(g => g.First())
.Select(o => new ProductMatch
{
productSKU = o.option1Code,
productPrice = o.price,
option1Desc = o.option1Desc
}).ToList();
Alternatively, if you use linq heavily and are open to using libraries, there is morelinq that gives you DistinctBy() extension and several other useful extensions.

queries in entity framework

i have written the following query and it is giving error Unable to cast object of type
System.Data.Objects.ObjectQuery'[ITClassifieds.Models.Viewsearch]' to type 'ITClassifieds.Models.Viewsearch'.
my code is as follows
if (zipcode.Contains(","))//opening of zipcode conatins comma
{
do
{
zipcode = zipcode.Replace(" ", " ");
zipcode = zipcode.Replace(", ", ",");
} while (zipcodecity.Contains(" "));
char[] separator = new char[] { ',' };
string[] temparray = zipcode.Split(separator);
var zipcd = (from u in db.ZipCodes1
where u.CityName == temparray[0] && u.StateAbbr == temparray[1] && u.CityType == "D"
select new Viewsearch
{
Zipcode = u.ZIPCode
}).Distinct();
Viewsearch vs = (Viewsearch)zipcd;
if (zipcd.Count() > 0)
{
zipcode = vs.Zipcode;
locations = "";
}
else
{
tempStr = "";
zipcode = "";
}
}
You need to do
If it will always exist:
Viewsearch vs = zipcd.First()
If not use, and then check for null before using
Viewsearch vs = zipcd.FirstOrDefault()
You could also use Single if there will always be 1 or None.
The Distinct method returns an enumerable collection (in your case, and ObjectQuery<T>, which may contain more than one element. You can't typecast that directly to an item in the collection, you need to use one of the IEnumerable methods to get it:
Viewsearch vs = zipcd.SingleOrDefault();
if ( vs != null )
{
zipcode = vs.Zipcode;
locations = String.Empty;
}
else
{
zipcode = String.Empty;
tempStr = String.Empty;
}
SingleOrDefault will throw an exception if there is more than one item in the collection; if that's a problem, you can also use FirstOrDefault to grab the first item, as one example.
Also, unrelated to your question, but you don't need the temporary array variable for your string separators. The parameter to the Split method is a params array so you can just call it like this:
string[] temparray = zipcode.Split(',');
Replace the zipcd query with:
var cityName = temparray[0];
var stateAbbr = temparray[1];
Viewsearch vs = new Viewsearch {
Zipcode = db.ZipCodes1.Where(u.CityName == cityName && u.StateAbbr == stateAbbr && u.CityType == "D").First().ZIPCode
};

Resources