Hello I am a beginner in ASP.NET
I have a variable checklistsss which was the list of my CheckList. here is the code:
var checkListss = (from u in _userManager.ClearanceCheckListRepository.GetQueryable().Where(x => x.ClearanceId == userId.ClearanceId) select new { clearanceCheckListId = u.ClearanceCheckListId }).ToList();
Now, I want the variable checkListss will put in the where clause at this code:
var due = from checkListsddd in _userManager.DueRepository.GetQueryable().Where(x => x.ClearanceCheckListId == checkListss) select new { Item = checkListsddd.Label, Action = checkListsddd.Action };
to output the due variable in this code
var checkList = from checkLists in _userManager.ClearanceCheckListRepository.GetQueryable().Where(x => x.ClearanceId == userId.ClearanceId) select new { ClearanceSignatoryId = checkLists.ClearanceSignatoryId, ClearanceCheckListId = checkLists.ClearanceCheckListId, Item = checkLists.Item, Action = checkLists.Action, Due = due };
take note that the checkListss will output multiple checkListId
I dont know how to do this in asp.net
thank you for your answers
Without some more details I can only guess at the types but I think what you are missing is using Enumerable.Contains to check if the ID is in checkListss. Something like:
var checkListss = (from u in _userManager.ClearanceCheckListRepository.GetQueryable().Where(x => x.ClearanceId == userId.ClearanceId) select u.ClearanceCheckListId).ToList();
var due = from checkListsddd in _userManager.DueRepository.GetQueryable().Where(x => checkListss.Contains(x.ClearanceCheckListId)) select new { Item = checkListsddd.Label, Action = checkListsddd.Action };
Note that I changed checkListss to be a list of the Id type instead of a list of an anonymous type.
As a side note the mixing of the LINQ fluent and query syntax is a bit confusing to look at (subjectively) so I would stick to the fluent syntax more like:
var checkListss = _userManager.ClearanceCheckListRepository.GetQueryable()
.Where(x => x.ClearanceId == userId.ClearanceId)
.Select(x => ClearanceCheckListId)
.ToList();
var due = _userManager.DueRepository.GetQueryable()
.Where(x => checkListss.Contains(x.ClearanceCheckListId))
.Select(x => new { Item = x.Label, Action = x.Action })
.ToList();
Related
I am using the following Lambda expression to try and join two models (LyncUser) and (DDI) and only return the DDI numbers that exist in both models. In LyncUser the field is called LyncUser.DDI and in DDI it is called DDI.Number.
This works and returns a list of all DDI numbers that are used from LyncUsers controller.
var lyncDB = new LyncUserEntities();
return Json(lyncDB.lyncUsers
.Select(c => new { DDI = c.DDI }), JsonRequestBehavior.AllowGet);
When I change this to incorporate a join so only the DDI numbers are returned that exist in LyncUsers but do not exist in DDI it fails to bring anything back.
public JsonResult GetAvailableDDINumbers()
{
var lyncDB = new LyncUserEntities();
return Json(lyncDB.LyncUsers
.Join(lyncDB.DDIs, avail => avail.DDI, used => used.Number,
(used, avail) => new { used = used, avail = avail })
.Where(joined => joined.used.DDI == joined.avail.Number), JsonRequestBehavior.AllowGet);
}
only the DDI numbers (...) that exist in LyncUsers but do not exist in DDI
To me that means you want to return LyncUsers having a DDI that doesn't exist as DDI.Number.
Your code, an inner join, does exactly the opposite. It returns the entities where both values (DDI and Number) are equal. And apparently, at this moment, there aren't any meeting this condition.
To achieve what you want you should use a different statement:
return Json(lyncDB.LyncUsers
.Where(u => !lyncDB.DDIs.Any(ddi => ddi.Number == u.DDI)), JsonRequestBehavior.AllowGet);
This should currently return all lyncDB.LyncUsers.
I don't think you need Join at all as you are not using joined result.
Try this instead:
var lyncDB = new LyncUserEntities();
var result = lyncDB.lyncUsers
.Where(x => !lyncDB.DDIs.Any(y => y.Number == x.DDI))
.Select(x => new { DDI = x.DDI });
return Json(result, JsonRequestBehavior.AllowGet);
Also, split your code in multiple lines as #Nate Barbettini advises in comment. This will allow to inspect results in debug mode and to better understand what is going on.
I can't explain the code. Look at different behavior:
var project = DB.Project.Find(1000111);
project.MustLinkToMF = false;
// Includes id = 1000111; MustLinkToMF = false; - From Cache?
var projects1 = DB.Project.Select(p => p).ToList();
// Doesn't contain 1000111! - Not From Cache?
var projects2 = DB.Project.Where(p => p.MustLinkToMF == false).Select(p => p).ToList();
DB.SaveChanges();
How to get cached data, included my changes?
How Can I get projects2 using one simple query before SaveChanges?
Thank you!
You can navigate through entities in the first level cache:
ctx.ChangeTracker.Entries().Where(x => x.State == EntityState.Modified).Select(x => x.Entity).OfType<T>()
Just replace EntityState.Modified for what you want.
See an example here: https://weblogs.asp.net/ricardoperes/entity-framework-code-first-get-entities-from-local-cache-or-the-database
I am using Anonymous Typed List for Repeater in ASP.Net, but the problem is if in whole list there is any null or object with missing attributes, it does not process the next elements but just gives me exception. What i want is if any element in my whole list is having null value or missing value, it should be skipped simply. Just like if we use foreach loop we can check the objects or we can apply try catch to prevent exceptions. Is there some way for anonymous typed listing and their traversal.
Here is my anonymous typed list.
var newList = li.Select(p => new
{
p.Id,
Title = new util.AlertMaker().GetOfferHyperLink(p.Id, p.Text, true),
Status = new util.StatusCompiler().CompileStatus(Numerics.GetInt(p.Status)),
UserName=p.Member.UserName+"",
DateTimeTitle = Convert.ToDateTime(p.Date).ToString(),
});
You can use this approach. I have edited your code for UserName and DateTimeTitle property.
var newList = li.Select(p => new
{
p.Id,
Title = new util.AlertMaker().GetOfferHyperLink(p.Id, p.Text, true),
Status = new util.StatusCompiler().CompileStatus(Numerics.GetInt(p.Status)),
UserName=p.Member.UserName==null?string.empty: p.Member.UserName+" ",
DateTimeTitle =p.Date==null?string.Empty: Convert.ToDateTime(p.Date).ToString(),
});
The only reason I can see for your list to throw exceptions -- simply by iterating -- is if the methods you call (GetOfferHyperLink(), Numerics.GetInt(), etc) can't handle null values being passed in.
After fixing those, I would write your method like so:
var newList = li.Select(p => new
{
p.Id,
Title = new util.AlertMaker().GetOfferHyperLink(p.Id, p.Text, true),
Status = new util.StatusCompiler().CompileStatus(Numerics.GetInt(p.Status)),
UserName=p.Member.UserName+"",
DateTimeTitle = Convert.ToDateTime(p.Date).ToString()
}).Where(x => !String.IsNullOrEmpty(x.Title)
&& !String.IsNullOrEmpty(x.Status)
&& !String.IsNullOrEmpty(x.UserName)
&& !String.IsNullOrEmpty(x.DateTimeTitle));
I'm passing a string to a controller, and need the controller to search for ANY of the words passed, within the Title field of my database.
eg. id="outlook error message"
[HttpPost]
public JsonResult Lookup(string id)
{
List<string> listOfSearch = id.Split(' ').ToList();
var results = db.KS.Where(x => x.Title.Intersect(listOfSearch).Any());
This produces the following two errors:
Instance argument: cannot convert from 'string' to 'System.Linq.IQueryable<string>
'string' does not contain a definition for 'Intersect' and the best extension method overload 'System.Linq.Queryable.Intersect<TSource>(System.Linq.IQueryable<TSource>, System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments
Can anyone please advise what's wrong, or how to populate results with just a list of Titles that contain any of the words passed in?
Thanks, Mark
var results = db.KS.Where(x => listOfSearch.Any(item => x.Title.Contains(item)));
Update:
For LinqToSql:
var titles = db.KS.Select(item => item.Title)
.AsEnumerable()
.Where(title => listOfSearch.Any(word => title.Contains(word)));
you can try
List<string> listOfSearch = id.Split(' ').ToList();
var result = from item in db.KS
where listOfSearch.Any(v => item.Title.Contains(v))
select item;
or
var result = db.KS.Where(item => listOfSearch.Any(v => item.Title.Contains(v)));
Change the statement to:
db.KS.Intersect(....
KS returns you the IQueryable on which you can directly perform the intersection.
I have the following function that returns results from the database based on LINQ Expressions:
IQueryable<TEntity> FindAll<TEntity>(Expression<Func<TEntity, bool>> expression)
When I try pulling data from the function while using the .Any function from a list I get a null reference exception.
However when I pull the data without that specific condition and use the same .Any function in a for each loop everything works correctly.
Here is the call trying to use the .Any function which does not work:
var ppcReports = repository.FindAll<PPCReport>(
x => x.ClientId == clientId &&
(campaigns.Any(c=> c.Id == x.CampaignId))
).ToList();
And the way it does work properly:
var ppcReports = repository.FindAll<PPCReport>(
x => x.ClientId == clientId).ToList();
foreach (var item in ppcReports)
{
if (campaigns.Any(c => c.Id == item.CampaignId))
{
// do something
}
}
I was wondering why was this happening, am I doing something wrong is it just not possible to filter the results before the query finished?
By calling .ToList() before filtering the results it does work, so I suppose I cannot do such an operation on an IQueryable<T> implementation?
var ppcReports = repository.
FindAll<PPCReport>(x => x.ClientId == clientId).
ToList().
Where(w => campaigns.Any(c => c.Id == w.CampaignId)).
ToList();
Like those who commented, I'm surprised that you got a NullReferenceException rather than a complaint about not being able to compile that statement to SQL. However, the following code should let you do this in 1 query (and will do all filtering in SQL):
var campaignIds = (campaigns ?? Enumerable.Empty<Campaign>())
.Select(c => c.Id);
var ppcReports = repository
.FindAll<PPCReport>(pr => pr.ClientId == clientId
&& campaignIds.Contains(pr.CampaignId))
.ToList();
This should work in both EF and Linq-to-SQL.
Queryable.Any() returns an ArgumentNullException when the source is null, as documented here: https://msdn.microsoft.com/it-it/library/bb343630(v=vs.110).aspx