Linq Query Distinct Function do not work with DropdownList - asp.net

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.

Related

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.

Divide in a Linq to SQL query

How can I form a Linq to sql Query for this code in SQL, I tried several things. This is my basic code:
List<Movie> movies =
(from item in db.Movies select item).ToList<Movie>();
return movies;
This is what I want as a result.
select (Won/Total) as 'rankPercentage'
from dbo.Filmranking
order by rankPercentage desc
Thanks
var movies =
(from items in db.Movies
select new { RankPercentage = item.Won / item.Total })
.ToList();
At this point, movies will be a List<T> where T is a float or int depending on the underlying SQL type (which I cannot discern from your question). If you really want to project this back as a List<Movie>, you will need to project that as follows but your result is not likely to match your SQL table.
List<OtherMovieType> movies =
(from items in db.Movies
select new OtherMovieType() {
Name = item.Name,
RankPercentage = item.Won / item.Total
})
.ToList();
item.Won / db.Awards.Count
Is count a property? I think it is.
You need something called projection, something like this:
var result = db.Movies
.Select(x => new { title=x.Title, rank = (x.Won/x.Total) })
.OrderBy(x => x.rank);
EDIT Maybe you want the title to identify your records :)

Correctly structuring this LinqToSql code

Normally I use stored procedures / work in SQL so apologies if I get the terminology slightly off here..
I have a database, with 3 seperate tables, and I need to search multiple fields in each of the 3 tables.
Im sure that I am not doing this the mose effective way, initially I am trying to do it in simple seteps to understand it.
I have the following;
var foo1 = entities.table1.Where(a => a.bodyText.Contains(searchString) || a.pageTitle.Contains(searchString));
var foo2 = entities.table2.Where(b => b.newsArticle.Contains(searchString) || b.newsArticle.Contains(searchString));
var foo3 = entities.table3.Where(c => c.ImageDescriptionContains(searchString));
I need to combine all these results into a single repeater for display.
At this point all 3 sets of data are in seperate, unique collections of anonymous data. So whats the best way of converting these into a single coherent bindable source?
I was thinking of itereating through each list in turn, pulling out the fields I need to display and putting them in a new class, then binding a lsit of these classes to the repeater.
But it all seems a bit clunky to me.
Is there a way of doing the search across all 3 tables in one go, and returning just the fields I need from each table, with a common name (i.e. in SQL I could write
select b.newsArticle as myText,
or
select newsArticle, ''
to return the news article and an empty string).
This would combine:
var foos = foo1.ToList();
foos.AddRange(foo2);
foos.AddRange(foo3);
To get just what you want:
var myExtractedValues = foos.Select(x => new {
Article = !string.IsNullOrEmpty(x.newsArticle))
? x.newsArticle
: string.Empty});
I have used an anonymous type here but you could swap the new {} with a type of your own.
I reverse the operator on the IsNullOrEmpty but that is just a personal preference (I prefer how is reads.)
To get all the results in one go you'll need to define a common class that will be used by all three queries to store the result. This class may be as well anonymous but I'll name it just for clarity.
class Data
{
public string Text{ get; set;}
}
Now, in your code you'll fetch instances of Data from database and you can use Union:
using( var entities = new YourDataContext)
{
var foo1 = entities.table1
.Where(a => a.bodyText.Contains(searchString) ||
a.pageTitle.Contains(searchString))
.Select(a => new Data{ Text = a.bodyText});
var foo2 = entities.table2
.Where(b => b.newsArticle.Contains(searchString) ||
b.newsArticle.Contains(searchString))
.Select(b => new Data{ Text = b.newsArticle});
var foo3 = entities.table3
.Where(c => c.ImageDescription.Contains(searchString))
.Select(c => new Data{ Text = c.ImageDescription});
return foo1.Union(foo2).Union(foo3);
}

MvcMusicStore No elements in sequence

I am working through the Mvc Music Store tutorial and am stuck on this LINQ query as it keeps telling me that the sequence has no elements. My model matches the model in the tutorial and I have inserted data into it. I have modified it so instead of albums it is designs.
var genreModel = storeDB.DesignTypes.Include("Designs")
.Single(g => g.Name == designType); -> no elements in sequence
var viewModel = new StoreBrowseViewModel() {
Genre = genreModel,
Albums = genreModel.Designs.ToList()
};
return View(viewModel);
use FirstOrDefault instead of Single:
var genreModel = storeDB.DesignTypes.Include("Designs")
.FirstOrDefault(g => g.Name == designType);
From msdn:
Enumerable.Single Method
Returns the only element of a
sequence, and throws an exception if
there is not exactly one element in
the sequence.
You have more than one match item or no item.

Autocomplete extender 'extended' across entire data table

I have a request to create an auto complete that will search an data table. Is this achieveable quickly and simply or is it a case of writing a reasonable amount of code?
Originally, I have been using a webservice and linq to point at a single column's worth of data (IDDesc) and pull back the list of products:
Product.FinalProductsDataContext dbac = new Product.FinalProductsDataContext();
return dbac.tblProduct
.Where(r => r.Account== HttpContext.Current.Session["AccountKey"].ToString() && r.IDDesc.Contains(prefixText))
.Distinct()
.OrderBy(r => r.IDDesc)
.Select(r => r.IDDesc)
.Take(count)
.ToArray();
However, if I wish the autocomplete to look at all the columns, is it a case of repeating similar LINQ statements for each of the columns contained within the datatable or is there a 'quick fix'?
I personally don't think this is an ideal scenario but it is a request I must work towards.
Any help or advice, greatly appreciated.
Rather than trying to solve this entirely with LINQ (and repeating all those statements for each column in the table, as well as hitting the database repeatedly), I think I'd look to put something in the database to do the heavy lifting here.
You could create a view that takes the fields from the table and amalgamates them into one column e.g.
CREATE VIEW [dbo].[ProductView]
AS
SELECT CAST(ProductName AS NVARCHAR(50)) AS 'ProductColumn'
FROM dbo.Products
UNION
SELECT CAST(SupplierName AS NVARCHAR(50))
FROM dbo.Products
UNION
...
which if you added the view to your context would then allow you to modify your existing LINQ query and point it at that view e.g.:
Product.FinalProductsDataContext dbac = new Product.FinalProductsDataContext();
return dbac.ProductView
.Where(r => r.Account== HttpContext.Current.Session["AccountKey"].ToString() && r.ProductColumn.Contains(prefixText))
.Distinct()
.OrderBy(r => r.ProductColumn)
.Select(r => r.ProductColumn)
.Take(count)
.ToArray();

Resources