About Grails GORM's Where clause - grails

Just a simple question here
I uses the following WHERE query
def instance = ClassName.where{varone == 'A' &&
vartwo == 'B' && varthree == 'C'}.list()
And it returned me the object that i wanted --> ClassName(unsaved)
But when i tried to do the following
def instance2 = ClassName.where{varone == params.varone &&
vartwo == params.vartwo && varthree == params.varthree}.list()
It returned me the following which i couldn't do anything on it --->
grails.gorm.DetachedCriteria#somenumbershere
I don't understand what are the differences between these two. I need the 2nd query to return the same object as what the first query returned.

Related

Rails: Conditional statement with && and ||

I currently have this:
<% if h.ab_template.AB_filterParent == 0 && h.status != 'geo_enabled' %>
What I'd like to do is say whether if h.ab_template.AB_filterParent == 0 || nil. How would I do that?
I tried this but it wasn't working:
<% if (h.ab_template.AB_filterParent == 0 || nil) && h.status != 'geo_enabled' %>
Would love to know what I've mistyped or implemented incorrectly!
Cheers
If you are sure that h.ab_template.AB_filterParent will always be a number (can be wrapped by quotes), then you can try following
<% if h.ab_template.AB_filterParent.to_i == 0 && h.status != 'geo_enabled' %>
else, if there is a possibility that h.ab_template.AB_filterParent can be something like "abc", "0asd" etc then try:
<% if (h.ab_template.AB_filterParent.nil? || h.ab_template.AB_filterParent == 0) && h.status != 'geo_enabled' %>
Generally nil and zero shouldn't mean the same thing. Try to eliminate the possibility of AB_filterParent being nil before you hit this code, by assigning a default value of zero in your migration table. I don't know how your model is so I can't even show an example of how to do it.
The main problem of using to_i == 0 is that it only works if AB_filterParent is either an integer or nil.
0.5.to_i == 0
"asdasd".to_i == 0
So it's odd.
Another way is to have it initialized in an action or other model method or even after_create callback.

Trying to count numbers of topics under a forum board

Here is what I currently have:
#Model.TPGForumTopicQuery.Select(m => m.closed != true && m.deleted != true)
.Where(m => m.TPGForumBoardID == item.boardID).Count()
This returns an odd error:
An error occurred during the compilation of a resource required to service this request.
Please review the following specific error details and modify your source code appropriately.
If I remove the .Select it works without error and counts all of the topics under the forum board. But the topics can be marked 'closed' or 'active' and I need to omit those in the count.
The above code is within a #foreach loop. So item.boardID is talking about the Forum Board.
Do not do the filter in the Select. Do it in the Where:
#Model.TPGForumTopicQuery.Where(m => m.TPGForumBoardID == item.boardID && m.closed != true && m.deleted != true).Count()
A bit of optimization:
Rather than m.closed != true, do !m.closed
#Model.TPGForumTopicQuery.Where(m => m.TPGForumBoardID == item.boardID && !m.closed && !m.deleted).Count()
And rather than get the Count after the Where-clause, you can pass in the where-clause to the Count():
#Model.TPGForumTopicQuery.Count(m => m.TPGForumBoardID == item.boardID && !m.closed && !m.deleted)

How to get distinct value from the list

I have a List generated from Linq to Entities query. In which, I need to get a unique records based on BibId. I have tried changing the query but no help to get the unique records based on BibId.
Query
aa.NewBibContentsModel = (from x in db.BibContents
where (x.TagNo == "245" && x.NormValue == aa.CurrentTitle) || (x.TagNo == "020" && x.NormValue == aa.CurrentISBN) || (x.TagNo == "022" && x.NormValue == aa.CurrentISBN)
select new
{
BibId = x.BibId,
Title = (from a in db.BibContents where a.BibId == x.BibId && a.TagNo == "245" orderby a.Id ascending select a.NormValue),
//Tit = (from a in db.BibContents where a.BibId == line.BibId && a.TagNo == "245" && a.Sfld == "a" select a.NormValue).FirstOrDefault(),
Author = (from a in db.BibContents where a.BibId == x.BibId && splitted.Contains(a.TagNo) && a.NormValue != null select a.TagNo).FirstOrDefault(),
ISBN = (from a in db.BibContents where a.BibId == x.BibId && a.NormValue != null && (a.TagNo == "020" || a.TagNo == "022") orderby a.Id ascending select a.NormValue)
}).AsEnumerable().Select(x => new BibContentsModel
{
BibId = x.BibId,
Title = string.Join(" ", x.Title),
Author = string.Join(" ", (from a in db.BibContents where a.BibId == x.BibId && a.TagNo == x.Author orderby a.Id select a.NormValue)),
ISBN = string.Join(" ", x.ISBN)
}).ToList();
Any help to this problem will be appreciated.
Thanks
What you're trying to achieve is know as Distinct By. MoreLinq has a function for it. The syntax would look like:
(from x in db.BibContentsNo == "022")
... // your query
}).AsEnumerable()
.DistinctBy(x => x.BibId) // <= MoreLinq
What is does is group the records by BibId and take the first element of each group.
You can download MoreLinq as a NuGet package.

syntax error in simple LINQ statement

I am developing MVC app and I am using the LINQ in controller.
I am trying to get one rechord with below query, but its giving an error...
Approval oAP = new Approval();
oAP = db.Approvals.Where(e => (e.ApprovedBy.Id == loggedEmployee.Id) && (e.ReviewNo == oPaymentAdvice.ReviewCount));
Is there any wrong syntax ?
Got the answer
oAP = db.Approvals.Where(e => (e.ApprovedBy.Id == loggedEmployee.Id) && (e.ReviewNo == oPaymentAdvice.ReviewCount)).FirstOrDefault();
Change this
e.ApprovedBy.Id = loggedEmployee.Id
For
e.ApprovedBy.Id == loggedEmployee.Id
You're comparing not assigning values.
Also you may add this
oAP = db.Approvals.Where(e => (e.ApprovedBy.Id == loggedEmployee.Id) && (e.ReviewNo == oPaymentAdvice.ReviewCount)).FirstOrDefault();
Because i'm assuming that you want to return only one
Some remarks:
You should be able to drop the Where:
oAP = db.Approvals.FirstOrDefault(e => (e.ApprovedBy.Id == loggedEmployee.Id) && (e.ReviewNo == oPaymentAdvice.ReviewCount));
Personally, I try to avoid the First and FirstOrDefault functions, because if you know there is only one record and if you want to enforce this, you can use SingleOrDefault:
oAP = db.Approvals.SingleOrDefault(e => (e.ApprovedBy.Id == loggedEmployee.Id) && (e.ReviewNo == oPaymentAdvice.ReviewCount));
If you know there will always be (more than) one record, you can drop the 'OrDefault' part and use First() or Single().

asp.net mvc datettime linq check for empty

var postsidebar = from post in postrepository.GetAllPosts()
join pstmt in postrepository.GetAllPostMetas()
on post.int_PostId equals pstmt.int_PostId
where (post.int_PostTypeId == 4
&& post.int_PostStatusId == 2
&& post.int_OrganizationId == layoutrep.GetSidebarDetailById(SidebarDetailsId).int_OrganizationId)
&& (pstmt.vcr_MetaKey.Contains(filter) && pstmt.vcr_MetaValue.Contains("true")
&& (System.DateTime.Now >=
Convert.ToDateTime(pstmt.Post.PostMetas.FirstOrDefault(m =>
m.vcr_MetaKey == "Publish Date").vcr_MetaValue)))
select post;
how can i check for empty in this part in Date(it is giving error)
&& (System.DateTime.Now >= Convert.ToDateTime(pstmt.Post.PostMetas.FirstOrDefault(m =>
m.vcr_MetaKey == "Publish Date").vcr_MetaValue)))
You could try eliminated the possibility of an empty value first and then try your cast afterward.
&& pstmt.Post.PostMetas.FirstOrDefault(m =>
m.vcr_MetaKey == "Publish Date"
&& !string.IsNullOrEmpty(m.vcr_MetaValue))
&& (System.DateTime.Now >=
Convert.ToDateTime(pstmt.Post.PostMetas.FirstOrDefault(m =>
m.vcr_MetaKey == "Publish Date").vcr_MetaValue)))
Try this:
// declare the action for re-use
Func<PostMeta,bool> action = m => m.vcr_MetaKey == "Publish Date";
// then test for Any() before comparing anything
&& (pstmt.Post.PostMetas.Any(action) && System.DateTime.Now >= Convert.ToDateTime(pstmt.Post.PostMetas.First(action).vcr_MetaValue)))

Resources