asp.net mvc datettime linq check for empty - asp.net-mvc

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)))

Related

better way to write If statement with a lot of repeats in rails ruby

I have a table with 30 different columns and I am trying to write a method that calls on each column containing a value.
eg.
def add_details
customer = Customer.find self.customer_id
if self.room1.present? && self.room2.present? && self.room3.present? && self.room4.present? && self.room5.present? && self.room6.present? && self.room7.present? && self.room8.present? && self.room9.present? && self.room10.present? && self.room11.present? && self.room12.present? && self.room13.present? && self.room14.present? && self.room15.present? && self.room16.present? && self.room17.present? && self.room18.present? && self.room19.present? && self.room20.present? && self.room21.present? && self.room22.present? && self.room23.present? && self.room24.present? && self.room25.present? && self.room26.present? && self.room27.present? && self.room28.present? && self.room29.present? && self.room30.present?
elsif self.room.present? && self.room2.present? && self.room3.present? && self.room4.present? && self.room5.present? && self.room6.present? && self.room7.present? && self.room8.present? && self.room9.present? && self.room10.present? && self.room11.present? && self.room12.present? && self.room13.present? && self.room14.present? && self.room15.present? && self.room16.present? && self.room17.present? && self.room18.present? && self.room19.present? && self.room20.present? && self.room21.present? && self.room22.present? && self.room23.present? && self.room24.present? && self.room25.present? && self.room26.present? && self.room27.present? && self.room28.present? && self.room29.present?
room = Room.find self.room
.....
room29 = ... end end
This is a whole lot of repeating myself and I know ruby is dynamic so there should be a way to increment the numbers with like a for loop and it would still work. I dont know if anyone has a better way to write this
Well you can do something like this:
if (up_to_29 = (1..29).all?{|i| send("column#{i}").present? }) && column30.present?
# update_columns column1: ...
elsif up_to_29
# update_columns column1: ...
Options 1: Assume that all model attributes need to validate
validate_needed_columns = Model.attribute_names
while validate_needed_columns.present? do
if validate_needed_columns.all?{ |c| Model[c].present? }
Model.update_columns(<Hash here>)
break
end
validate_needed_columns.pop
end
Options 2: Use mapping to set which columns need to update
validate_needed_columns = {
column_name_1: value_to_update_1,
...
column_name_n: value_to_update_n
}
validate_needed_column_keys = validate_needed_columns.keys
while validate_needed_column_keys.present? do
if validate_needed_column_keys.all?{ |c| Model[c].present? }
Model.update_columns(<Use mapping to set value here>)
break
end
validate_needed_column_keys.pop
end
You can use a range of numbers to loop through and call "column_#{i}" on each one. The all? method will return true if every iteration of the loop is true. Try something like this:
if (1..30).all?{|index| self.send("column#{index}")&.present? }
#...
elsif (1..29).all?{|index| self.send("column#{index}")&.present? }
#...

About Grails GORM's Where clause

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.

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().

Resources