pass decimal column value to populate results from a table using linq query - entity-framework

I have a product table with 20 column. There is a column 'Width' which is decimal data type. I have been calling particular width value in web api controller to populate results. As an example,width values are like below:
Width values
1 0.0015
2 1.0000
3 0.0063
4 1.0100
5 2.0000
6 2.0630
public HttpResponseMessage GetclassByWidthList(Decimal cWidth)
{
using (CrossReferenceTool1Entities cls1 = new CrossReferenceTool1Entities())
{
**var query = (from u in cls1.Products where (u.PrivateOnly == false && u.SelectionTool == true && u.ProductTypeID == 2 && (u.ProductFamilyID == 11 || u.ProductFamilyID == 12 || u.ProductFamilyID == 58 || u.ProductFamilyID == 59 || u.ProductFamilyID == 92) && **u.Width == cWidth**) select u.Class).Distinct().ToList()**;
HttpResponseMessage res;
res = Request.CreateResponse(HttpStatusCode.OK, query);
return res;
}
}
method is working fine. results are reflected if width value is "1.0000" OR "2.0000" but for other values of width it is not populating any result.
Please help me on above query where other decimal values with precision will populate result.
i have tried in browser to populate result:
1.
http://localhost:55481/api/KendoCascading/GetclassByWidthList/1 - result is poupulating
`http://localhost:55481/api/KendoCascading/GetclassByWidthList/1.01 - http-404 error showing

For debugging, your decimal data of Cwidth is being truncated, Please check

As per Ehasanul's suggestion i Just modified my method with putting extra "/" last of that route path
[Route("**api/KendoCascading/GetclassByWidthList/{cWidth:decimal}/**")]
public HttpResponseMessage GetclassByWidthList(decimal cWidth)
{
using (CrossReferenceTool1Entities cls1 = new CrossReferenceTool1Entities())
{
var query = (from u in cls1.Products where (u.PrivateOnly == false && u.SelectionTool == true && u.ProductTypeID == 2 && (u.ProductFamilyID == 11 || u.ProductFamilyID == 12 || u.ProductFamilyID == 58 || u.ProductFamilyID == 59 || u.ProductFamilyID == 92) && u.Width == cWidth) select u.Class).Distinct().ToList();
HttpResponseMessage res;
res = Request.CreateResponse(HttpStatusCode.OK, query);
return res;
}
}
call that url in my angular service http.get method with adding extra "/" in last.
this.getclsWidthList3 = function (cWidth) {
var res;
if (cWidth !== 0.0000) {
res = $http.get("/api/KendoCascading/GetclassByWidthList"+ "/"+ cWidth+"/");
return res;
}
};
and its working great.

Related

Accent insensitive in filter backend to datatable in ASP.NET MVC 5

I made a method on the back-end side to handle the filter of my datatable.
On the other hand, this one does not manage the accents of the French language, so if I have "école" and I write "ecole" it cannot find it.
I found this method on another question on stackoverflow
public static String RemoveDiacritics(this String s)
{
String normalizedString = s.Normalize(NormalizationForm.FormD);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < normalizedString.Length; i++)
{
Char c = normalizedString[i];
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
and it works, but only for part of my problem. It works on the letter or the word that is written in the search, but I am not able to apply it in my linq query, so with the .RemoveDiacritics() method my "école" becomes "ecole", but I don't am not able to apply it in the column of my table and it always looks for "école".
Here the code for the search:
if (search != null)
{
int n;
search = search.Trim();
var isNumeric = int.TryParse(search, out n);
if (isNumeric)
{
IdFilter = n;
query = query.Where(x => x.UsagerId == IdFilter || x.Niveau == IdFilter);
}
else if (search != "")
{
// this line work
textFilter = search.ToLower().RemoveDiacritics();
// This is the full line, but absolutely takes the accents out to get the right information out
// query = query.Where(x => x.Nom.ToLower().Contains(textFilter) || x.Prenom.ToLower().Contains(textFilter) || x.Username.ToLower().Contains(textFilter) || x.Email.ToLower().Contains(textFilter) || x.EtabNom.ToLower().Contains(textFilter) || x.ActifStatut.ToLower().Contains(textFilter));
// This is the line that will replace the line above, which I try and it doesn't work ( this part: x.Prenom.ToLower().RemoveDiacritics())
query = query.Where(x => x.Prenom.ToLower().RemoveDiacritics().Contains(textFilter));
}
}
This is the basic query:
IQueryable<ListeUsagers> query = (from u in db.USAGERs
join e in db.ETABLISSEMENTs on u.USAGER_INST equals e.ETAB_CODE
where u.USAGER_INST == instId && u.USAGER_NIVEAU > 3 && u.USAGER_NIVEAU < 5 //&& u.USAGER_ACTIF == 1
select new ListeUsagers()
{
UsagerId = u.USAGER_id,
Nom = u.USAGER_NOM,
Prenom = u.USAGER_PRENOM,
EtabCode = e.ETAB_CODE,
EtabNom = e.ETAB_NOM_COURT,
EtabType = e.ETAB_TYPE,
Niveau = u.USAGER_NIVEAU,
Username = u.USAGER_USERNAME,
UserPassword = u.USAGER_MP,
DateCreation = u.USAGER_DATE_INSC,
Sexe = u.USAGER_SEXE,
Lang = u.USAGER_LANGUE,
Telephone = u.USAGER_TELEPHONE,
Email = u.USAGER_EMAIL,
FonctionTravail = u.USAGER_FONCTION,
LieuTravail = u.USAGER_LIEUTRAVAIL,
Note = u.USAGER_NOTE,
Actif = u.USAGER_ACTIF,
ActifStatut = u.USAGER_ACTIF == 0 ? "Inactif" : "Actif"
});
This is the error:
LINQ to Entities does not recognize the method 'System.String RemoveDiacritics(System.String)' method, and this method cannot be translated into a store expression.
There's built-in functionality to do this in entityframework: https://learn.microsoft.com/en-us/ef/core/miscellaneous/collations-and-case-sensitivity if you're using EF 5+
You'll want an accent insensitive collation ("AI", not "AS" in the examples on that page.)

Entity Framework check result null

I am using this query:
var result = from r in db.Registrations
join u in db.UserTypes on r.UserTypeId equals u.UserTypeId
where r.Email.ToLower()==model.LoginEmail.ToLower() && r.Password.ToLower() == model.Password.ToLower()
select new { r,u};
Here how can I check that if no record is found? If so, then
if(result == null)
// no record found
else
// record found
You can use Any or Count extension method:
if(!result.Any())
///norecord found
else
//record found
Using Count would be:
if(result.Count()==0)
///norecord found
else
//record found
First what you assign to a result is just IQueryable so it's query and you need to execute it first. So I suggest renaming it to query and then do it like this:
var query= from r in db.Registrations
join u in db.UserTypes on r.UserTypeId equals u.UserTypeId
where r.Email.ToLower()==model.LoginEmail.ToLower() && r.Password.ToLower() == model.Password.ToLower();
select new { r,u};
var result = query.FirstOrDefault(); // gives first result or null
if (result == null) {
// no record
} else {
// record found and is in result
}

how to debug EF 5 null reference exception?

I am getting a null refrence exception when im filtering EF but I am absolultely clueless.
public IEnumerable<TonalityBatchModel> GetTonalityBatch(int briefID)
{
try
{
var brief = NeptuneUnitOfWork.Briefs.FindWhere(b => b.ID == briefID).FirstOrDefault();
if (brief != null && brief.TonalityCriteria != null)
{
return brief.TonalityCriteria.TonalityBatches
.Select(b => new TonalityBatchModel()
{
BriefID = b.BriefID,
Status = b.TonalityCriteria.IsActive == true ?"Active":"Ended",
BatchID = b.ID,
CompetitorID = b.BriefCompetitorID,
Competitor = brief.BriefCompetitors.Where(i=>i.ID == b.BriefCompetitorID).Select(c=>c.Organisation.Name).First(),
Size = b.BatchSize,
StartDate = b.StartDate,
EndDate = b.EndDate,
IsPublished = b.Lookup_TonalityBatchStatus.ID == (int)TonalityBatchStatus.Published?"Yes":"No",
IsCompleted = b.Lookup_TonalityBatchStatus.ID == (int)TonalityBatchStatus.Completed ? "Yes" : "No",
IsAssigned = b.Lookup_TonalityBatchStatus.ID == (int)TonalityBatchStatus.Allocated ? "Yes" : "No",
ImportantCount = b.TonalityItems.Count(i=> i.IsImportant),
ArticlesCount = b.TonalityItems.Count,
FavourableCount = b.TonalityItems.Count(i => i.Lookup_TonalityScoreTypes.ID ==(int)TonalitySourceType.Favourable),
UnfavourableCount = b.TonalityItems.Count(i => i.Lookup_TonalityScoreTypes.ID ==(int)TonalitySourceType.Unfavourable),
NeutralCount = b.TonalityItems.Count(i => i.Lookup_TonalityScoreTypes.ID ==(int)TonalitySourceType.Neutral)
}).ToList();
}
return new List<TonalityBatchModel>();
}
catch (Exception ex)
{
Logger.Error(ex);
throw;
}
}
You'll need to reduce your query to a simpler query, and then start building it back up again until the NullReferenceException occurs. Looking at your code, here are some likely places (I'm making some assumptions since I don't know everything about your model):
Competitor = brief.BriefCompetitors.Where(i=>i.ID == b.BriefCompetitorID).Select(c=>c.Organisation.Name).First()
BriefCompetitors could be null. c.Organisation could be null.
IsPublished = b.Lookup_TonalityBatchStatus.ID == (int)TonalityBatchStatus.Published?"Yes":"No",
(and other similar lines) b.Lookup_TonalityBatchStatus might be null.
ImportantCount = b.TonalityItems.Count(i=> i.IsImportant),
(and other similar lines) b.TonalityItems might be null.
I believe this is because your count is returning null records. I could be wrong but the SQL that's being produced here is something like:
INNER JOIN TonalityItems i on i.Lookup_TonalityScoreTypes == x
Where x is the value of (int)TonalitySourceType.Favourable. Because this join has no matching results there is nothing to do a count on. You could try adding ?? 0 to the end of the query:
FavourableCount = b.TonalityItems.Count(i => i.Lookup_TonalityScoreTypes.ID ==(int)TonalitySourceType.Favourable) ?? 0,

how to change multiple function arguments into coffescrpt

here is the javascript:
$inputor.on("keyup.inputor", $.proxy(function(e) {
var stop_key = e.keyCode == 40 || e.keyCode == 38
lookup = !(this.view.isShowing() && stop_key)
if (lookup) this.lookup()
},this))
how can i translate it into coffesscript? the first argument of a function like $.proxy is a function and still have a second one.
my solution is assign a variable for the first argument, the function, and poss it to $.proxy.
but i want a better solution.
coffeescript:
??????
Instead of using the jQuery.proxy function, you could use the CoffeeScript fat arrow => since the context you're trying to use is this
$inputor.on "keyup.inputor", (e) =>
stop_key = e.keyCode == 40 || e.keyCode == 38
lookup = !(#view.isShowing() && stop_key)
#lookup() if lookup

Using an existing IQueryable to create a new dynamic IQueryable

I have a query as follows:
var query = from x in context.Employees
where (x.Salary > 0 && x.DeptId == 5) || x.DeptId == 2
order by x.Surname
select x;
The above is the original query and returns let's say 1000 employee entities.
I would now like to use the first query to deconstruct it and recreate a new query that would look like this:
var query = from x in context.Employees
where ((x.Salary > 0 && x.DeptId == 5) || x.DeptId == 2) && (x,i) i % 10 == 0
order by x.Surname
select x.Surname;
This query would return 100 surnames.
The syntax is probably incorrect, but what I need to do is attach an additional where clause and modify the select to a single field.
I've been looking into the ExpressionVisitor but I'm not entirely sure how to create a new query based on an existing query.
Any guidance would be appreciated. Thanks you.
In an expression visitor you would override the method call. Check if the method is Queryable.Where, and if so, the methods second parameter is a quoted expression of type lambda expression. Fish it out and you can screw with it.
static void Main()
{
IQueryable<int> queryable = new List<int>(Enumerable.Range(0, 10)).AsQueryable();
IQueryable<string> queryable2 = queryable
.Where(integer => integer % 2 == 0)
.OrderBy(x => x)
.Select(x => x.ToString());
var expression = Rewrite(queryable2.Expression);
}
private static Expression Rewrite(Expression expression)
{
var visitor = new AddToWhere();
return visitor.Visit(expression);
}
class AddToWhere : ExpressionVisitor
{
protected override Expression VisitMethodCall(MethodCallExpression node)
{
ParameterExpression parameter;
LambdaExpression lambdaExpression;
if (node.Method.DeclaringType != typeof(Queryable) ||
node.Method.Name != "Where" ||
(lambdaExpression = ((UnaryExpression)node.Arguments[1]).Operand as LambdaExpression).Parameters.Count != 1 ||
(parameter = lambdaExpression.Parameters[0]).Type != typeof(int))
{
return base.VisitMethodCall(node);
}
return Expression.Call(
node.Object,
node.Method,
this.Visit(node.Arguments[0]),
Expression.Quote(
Expression.Lambda(
lambdaExpression.Type,
Expression.AndAlso(
lambdaExpression.Body,
Expression.Equal(
Expression.Modulo(
parameter,
Expression.Constant(
4
)
),
Expression.Constant(
0
)
)
),
lambdaExpression.Parameters
)
)
);
}
}
}