This code works only if I complete the 3 fields:
website, author, and content.
I want to complete 1 field, 2 fields or 3 fields (non completed fields are null) and search according to that
var posts = from p in db.Posts
where ((p.PostDate >= fd && p.PostDate <= td)
&& p.WebSite.Equals(WebSite)
&& p.PostAuthor.Contains(Author)
&& p.PostText.Contains(Content)
|| WebSite == null || Author == null || Content == null)
select p;
I tried this code but don't working too:
var posts = from p in db.Posts
select p;
if (WebSite != null)
{
posts = from p in db.Posts
where p.WebSite.Equals(WebSite)
select p;
}
if (Author != null)
{
posts = from p in db.Posts
where p.PostAuthor.Contains(Author)
select p;
}
if (Content != null)
{
posts = from p in db.Posts
where p.PostText.Contains(Content)
//Count and date is missing
select p;
}
return View("Index", posts);
I need like this for 1 parameter but for 3:
var posts = from p in db.Posts
where p.PostTitle.Contains(searchTerm) || searchTerm==null
select p;
return View(posts);
First you need to prepare non filtered IQueryable object without selecting the output:
IQueryable<Post> query = from p in posts;
Then apply filter according to your filter conditions
if (webSite != null)
{
posts = posts.Where(p => p.WebSite.Contains(webSite));
}
if (author != null)
{
posts = posts.Where(p => p.PostAuthor.Contains(author));
}
Finnaly run query
var result = posts.ToArray();
Another approach is to create fulltext index on the table and search by fulltext in indexed columns. It has better results then searching in the three fields separately.
Change your code to this:
var posts = from p in db.Posts
select p;
if (!string.IsNullOrEmpty(WebSite))
{
posts = from p in posts
where p.WebSite.Equals(WebSite)
select p;
}
if (!string.IsNullOrEmpty(Author))
{
posts = from p in posts
where p.PostAuthor.Contains(Author)
select p;
}
if (!string.IsNullOrEmpty(Content))
{
posts = from p in posts
where p.PostText.Contains(Content)
//Count and date is missing
select p;
}
return View("Index", posts.ToList());
An empty string is not the same as a null string.
Edit: you should probably execute the query before sending it to the view.
Using LINQ to Entities:
var posts = db.Posts.AsQueryable();
if (!string.IsNullOrEmpty(WebSite))
posts = posts.Where(p => p.WebSite.Equals(WebSite));
if (!string.IsNullOrEmpty(Author))
posts = posts.Where(p => p.PostAuthor.Contains(Author));
if (!string.IsNullOrEmpty(Content))
posts = posts.Where(p => p.PostText.Contains(Content));
return View("Index", posts.ToList());
Solution:
var posts = from p in db.Posts
where ((string.IsNullOrEmpty(WebSite) || p.WebSite.Equals(WebSite))
&& (string.IsNullOrEmpty(Author) || p.PostAuthor.Contains(Author))
&& (string.IsNullOrEmpty(Content) || p.PostText.Contains(Content))
)
select p;
Try the following:
var posts = from p in db.Posts
where ((p.PostDate >= fd && p.PostDate <= td)
&& ((string.IsNullOrEmpty(WebSite) || p.WebSite.Equals(WebSite))
|| (string.IsNullOrEmpty(Author) || p.PostAuthor.Contains(Author))
|| (string.IsNullOrEmpty(Content) || p.PostText.Contains(Content)))
)
select p;
Just replace db.Posts with posts in the three conditional searches, so for the first one:
if (WebSite != null)
{
posts = from p in posts
where p.WebSite.Equals(WebSite)
select p;
}
Related
I'm trying to fetch the record from 3 tables by comparing the user Logged in name
Here is my code:
public ActionResult MeritList() //departmental merit listed students details with status 1
{
var username= HttpContext.Session["UserName"];
List<StdListModel> model = new List<StdListModel>();
var query = (from s in Context.tblStdDetails
join e in Context.tblStdEnrollments on s.ID equals e.StdReg_ref_id
//join d in Context.tblDepartments on e.Depart_ref_id equals d.ID
where s.Status == '1' && e.tblDepartment.DepartName == username
select new StdListModel
{
ID = s.ID,
Name = s.Name,
FatherName = s.FatherName,
CNIC = s.CNIC,
FormNo = s.FormNo,
DiaryNo = s.DiaryNo,
Status = s.Status
}).ToList();
foreach(var item in query)
{
model.Add(new StdListModel()
{
ID=item.ID,
Name=item.Name,
FatherName=item.FatherName,
CNIC=item.CNIC,
FormNo=item.FormNo,
DiaryNo=item.DiaryNo
});
}
return View(model);
}
Also Tried this Query
var query = (from s in Context.tblStdDetails
join e in Context.tblStdEnrollments on s.ID equals e.StdReg_ref_id
join d in Context.tblDepartments on e.Depart_ref_id equals d.ID
where s.Status == '1' && d.DepartName.Equals(username)
select new StdListModel
{
ID = s.ID,
Name = s.Name,
FatherName = s.FatherName,
CNIC = s.CNIC,
FormNo = s.FormNo,
DiaryNo = s.DiaryNo,
Status = s.Status
}).ToList();
But it does not return anything model=0, query =0, the database has right values and I don't get any error either.
please check username with tolower() and trim function.
e.tblDepartment.DepartName.ToLower().Trim() == username.ToLower().Trim()
or
e.tblDepartment.DepartName.ToLower().Trim().equals(username.ToLower().Trim())
I got the problem. It is in
s.Status == '1'
I just changed it into
s.Status == 1
and it works fetch the data from the database.
model.ListManagerReviewerMapping = (from a in wallet.OM_Employee
join m in wallet.APPR_ManagerMapping
on a.AssociateId equals m.AssociateId
where m.ManagerId==Context.UserId.Value **into** MM
from leftjoinresult in M.DefaultIfEmpty()
where a.CompanyId == Context.CompanyId && (a.TermStatus == "L" || a.SeparationDate > DateTime.Today)
select new ManagerAndReviewerMappingModel.ManagerAndReviewerMapping()
{
Photo = (photoUrl + "?AssociateCode=" + a.AssociateCode),
AssociateId = a.AssociateId,
AssociateCode = a.AssociateCode,
AssociateName = a.AssociateName
}).ToList();
You need to use Where extension method for first query, as the query uses left join with DefaultIfEmpty (note that you can't use into after where clause since where must be followed with select to finish the query):
model.ListManagerReviewerMapping = (from a in wallet.OM_Employee
join m in wallet.APPR_ManagerMapping.Where(x => x.ManagerId == Context.UserId.Value)
on a.AssociateId equals m.AssociateId into MM
from leftjoinresult in MM.DefaultIfEmpty()
where a.CompanyId == Context.CompanyId && (a.TermStatus == "L" || a.SeparationDate > DateTime.Today)
select new ManagerAndReviewerMappingModel.ManagerAndReviewerMapping()
{
Photo = (photoUrl + "?AssociateCode=" + a.AssociateCode),
AssociateId = a.AssociateId,
AssociateCode = a.AssociateCode,
AssociateName = a.AssociateName
}).ToList();
Similar issues:
LINQ LEFT JOIN where clause not working
LINQ Left Join And Right Join
//Remove brackets and .ToList();
model.ListManagerReviewerMapping = from a in wallet.OM_Employee
join m in wallet.APPR_ManagerMapping
on a.AssociateId equals m.AssociateId
where m.ManagerId==Context.UserId.Value **into** MM
from leftjoinresult in M.DefaultIfEmpty()
where a.CompanyId == Context.CompanyId && (a.TermStatus == "L" || a.SeparationDate > DateTime.Today)
select new ManagerAndReviewerMappingModel.ManagerAndReviewerMapping()
{
Photo = (photoUrl + "?AssociateCode=" + a.AssociateCode),
AssociateId = a.AssociateId,
AssociateCode = a.AssociateCode,
AssociateName = a.AssociateName
};
I am not much familiar with EF. I want to group rows based on IDs. I acheive this in SQL but I am getting some Issues with group by while implementeing in EF.
public ActionResult PropertyListing()
{
if (Session["UserID"] == null)
{
return RedirectToAction("Login", "Property");
}
return View();
}
public JsonResult GetSpurts()
{
PropertySpurts property;
List<PropertySpurts> listProperty = new List<PropertySpurts>();
var userID = Convert.ToInt32(Session["UserID"].ToString());
// IEnumerable<tblPropertyView> PropertyList;
var PropertyList = from p in dbEntity.tblPropertyViews
join c in dbEntity.tblProperties on p.PropertyID equals c.ID into j1
from j2 in j1.DefaultIfEmpty()
group j2 by p.PropertyID into grouped
select new { ParentId = grouped.Key, Count = grouped.Count(t => t.ID != null) };
if (PropertyList != null)
{
foreach (var item in PropertyList)
{
property = new PropertySpurts();
property.ID = (int)item.ParentId;
property.Title = item.tblProperty.Title;
listProperty.Add(property);
}
}
return Json(listProperty, JsonRequestBehavior.AllowGet);
}
PropertyID in tblPropertyView is Foreign Key to tblProperty ID. I want to get title of Property from tblProperty. Please help me to find Title and Count of PropertyViews
TIA
[SOLVED]
var PropertyList = from p in dbEntity.tblPropertyViews
join c in dbEntity.tblProperties on p.PropertyID equals c.ID into j1
from j2 in j1.DefaultIfEmpty()
group j2 by new
{
p.PropertyID,
p.tblProperty.Title
} into grouped
select new
{
ParentId = grouped.Key.PropertyID,
Title = grouped.Key.Title,
Count = grouped.Count(t => t.ID != null)
};
This solves my issue. But I want this should be orderby count.
var PropertyList = (from p in dbEntity.tblPropertyViews
join c in dbEntity.tblProperties on p.PropertyID equals c.ID into j1
from j2 in j1.DefaultIfEmpty()
group j2 by new
{
p.PropertyID,
p.tblProperty.Title
} into grouped
select new
{
ParentId = grouped.Key.PropertyID,
Title = grouped.Key.Title,
Count = grouped.Count(t => t.ID != null)
}).OrderByDescending(x => x.Count);
I have never used JOIN(INNER, OUTER), and I don't have any idea when is the best scenario:
Here I have two examples of ActionResults that uses 2 or 3 queries to get an object, isn't better to use a JOIN instead?
First Example:
public ActionResult JobTags(int id)
{
var jobTagsList = (from j in db.JobTags
where j.JobID == id
select j.TagID).ToList();
var tags = (from j in db.Tags
where jobTagsList.Contains(j.ID.ToString())
select j).ToList();
return View(tags);
}
Can I just JOIN this two tables and select that j at the end?
Second Example:
public ActionResult ImageListWhoApp(int id)
{
//We get here the ID from Job page using dbo.Jobs
var userIdList = (from j in db.Jobs
where j.ID == id
select j.ID.ToString()).ToList();
//We get here who applied at this job using dbo.AppliedJobs
var appJobIdList = (from j in db.AppliedJobs
where userIdList.Contains(j.JobID.ToString())
select j.UserID).ToList();
//Finally we get here the avatars of the user who applied at the job
//We are using this as a hyperlink to user profile.
var appUserImage = (from j in db.Images
where appJobIdList.Contains(j.UserID.ToString())
select j).ToList();
return View(appUserImage);
}
Isn't this approach getting ridiculous? Or is normal to do stuff like this in this manner? How do I make a JOIN from this 3 SQL statements? Is it possible? is it the better way?
Thank you for your time!
You don't need joins. You can use navigation properties:
var tagsQry =
from tag in db.Tags
where tag.JobTag.JobID == id
select tag;
var userImageQry =
from img in db.Images
from appJob in db.AppliedJobs
where (img.UserID == appJob.UserID) && (appJob.Job.ID == id)
select img;
Even if you have no navigation properties, you don't need joins:
var tagsQry =
from tag in db.Tags
from jobTag in sb.JobTags
where (jobTag.JobID == id) && (tag.ID == jobTag.TagID)
select tag;
var userImageQry =
from img in db.Images
from appJob in db.AppliedJobs
from job in db.Jobs
where (img.UserID == appJob.UserID) && (appJob.JobID == job.ID) && (job.ID == id)
select img;
You can however use joins if you prefer the syntax. The DB side query execution plan will be exactly the same:
var tagsQry =
from tag in db.Tags
join jobTag in sb.JobTags on tag.ID equals jobTag.TagID
where (jobTag.JobID == id)
select tag;
var userImageQry =
from appJob in db.AppliedJobs
join img in db.Images on appJob.UserID equals img.UserID
join job in db.Jobs on appJob.JobID equals job.ID
where (job.ID == id)
select img;
In the second example you only need the query (or join) to Jobs if you don't have a foreign key constraint on AppliedJobs.JobID. If you do, you can compare AppliedJobs.JobID directly with id.
I want to write if condition inside where clause. because if first name or last name is null I don't wani to add it in where clause . other wise I want to add it.
so I write
var query1 = from opv in _opvRepository.Table
join o in _orderRepository.Table on opv.OrderId equals o.Id
join gr in _graduandRepository.Table on opv.graduand_id equals gr.graduand_id
join pv in _productVariantRepository.Table on opv.ProductVariantId equals pv.Id
join p in _productRepository.Table on pv.ProductId equals p.Id
where (opv.ceremony_id == ceremony_id) &&
(!o.Deleted) && (opv.IsHireItem == true) &&
(!p.Deleted) &&
(!pv.Deleted) && (opv.ceremony_id == ceremony_id)
// group opv by opv.OrderId into g
select new
{
opvTable = opv,
grTable = gr,
};
// This is not working. I have problem in here. How to add this??
if (!String.IsNullOrEmpty(Fname))
query1 = query1.Where(grTable = > grTable.first_name == Fname);
var result = query1.ToList().Select(x =>
{
return new HireItemReportLine()
{
OrderId = x.opvTable.OrderId,
OrderDate=x.opvTable.Order.CreatedOnUtc,
Amount= x.opvTable.Order.OrderSubtotalExclTax,
PaymentMethod = x.opvTable.Order.PaymentMethodSystemName,
paidDate = x.opvTable.Order.CreatedOnUtc,
Fname = x.grTable.first_name,
MName = x.grTable.middle_name,
LName = x.grTable.last_name,
};
}).ToList();
What is the wrong with my cording??
Note that your original query selects an anonymous type with two properties: opvTable and grTable. So, you need to use one of those properties in the subsequent Where clause, like this:
query1 = query1.Where(item => item.grTable.first_name == Fname);