JsonResult from lambda expression using join - asp.net

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.

Related

List in where clause in ASP.net

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

Get all columns by eager loading

I created a table with relation with ApplicationUser and when I want to get with eager-loading, I could not get all columns from that table my search base on user authentication.
var UserSites = await _SqldbContext.Users
.Where(x => x.UserName == User.Identity.Name)
.Include(x => x.sites)
.ToListAsync() ;
return Json(UserSites);
But in return I only get one row of that table with two columns
[{"sites":[{"id":1,"userId":"c0e8be95-535c-449c-9aa1-06702cd4c983"
but I have more rows with this userId and also here I get only two columns but I have more than two columns, I am not sure what is wrong here please help me.
I think ToListAsync() works properly and If you make break point you may see all data from your site but here I think Json does not show it properly, instead of start from User table in your example I started with your proposed table name sites (to get all data of this table)
var UserSites = await _SqldbContext.sites.Include(x => x.[Name Of User in relation table]).Where(y=>y.[Name Of User in relation table].UserName== User.Identity.Name)
.ToListAsync();
List<sites> siteObject=new List<sites>();
UserSites.ForEach(x =>
{
sites site = new sites() {
// fill property of your class
};
siteObject.Add(site);
});
return Json(siteObject);
I hope this code works for you.

Linq Query Distinct Function do not work with DropdownList

I want to assign Linq Query result to dropdownlist which contain a
Distinct function
My Code:-
var area = de.City_Area_View
.Select(m => new { m.Area_Id, m.Area_Name})
.Distinct()
.ToList();
drpfilter.DataTextField = "Area_Name";
drpfilter.DataValueField = "Area_Id";
drpfilter.DataSource = area;
drpfilter.DataBind();
Problem :- When I write this code then I get Below Error
Error:- The method 'Distinct' is not supported.
I get System.NotSupportedException.
I want to assign a Distinct name of area to the DropDownList
So please help me for this problem.
If your set is small enough (so you don't mind fetching all the values from the database), the simplest thing would be to force the distinct part to be performed locally:
var area = de.City_Area_View
.Select(m => new { m.Area_Id, m.Area_Name})
.AsEnumerable()
.Distinct()
.ToList();
AsEnumerable simply "changes" the expression type to IEnumerable<T> instead of IQueryable<T>, so that the compiler calls Enumerable.Distinct instead of Queryable.Distinct - and Enumerable.Distict will definitely work.

Search for any word in a Linq query

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.

Linq Query with .Any condition returns nullreference exception

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

Resources