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.
Related
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 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.
I'm using Tridion.ContentDelivery.DynamicContent.Query.
I'm trying to filter components and exclude some of them by the taxonomy keyword, my code:
List<Criteria> excludeCriteria = new List<Criteria>();
foreach (string keywordUri in excludeKeywords)
{
excludeCriteria.Add(new TaxonomyKeywordCriteria(categoryUri, keywordUri, false));
}
Criteria criteria = new NotInCriteria(new AndCriteria(excludeCriteria.ToArray())));
Query query = new Query(criteria);
The problem is, that in result I have a list that filtered only by one of TaxonomyKeywordCriteria. The first one criteria from excludeKeywords list are applied, and all others are ignored.
I'm not entirely sure, but I have a feeling when you add the Criteria like this you get a OR list somehow (you could check the debug log of the broker, that should have the query executed in there).
Can you try it the other way around, wrapping your TaxonomyKeywordCriteria in a NotInCriteria and adding those to the AndCriteria? So something like this:
List<Criteria> excludeCriteria = new List<Criteria>();
foreach (string keywordUri in excludeKeywords)
{
excludeCriteria.Add(new NotInCriteria(new TaxonomyKeywordCriteria(categoryUri, keywordUri, false)));
}
Criteria criteria = new AndCriteria(excludeCriteria.ToArray()));
Query query = new Query(criteria);
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);
}
I have a message table that self joins to itself where Message.ID == Message.Parent. So I have 1 Message with several ChildMessages. This is set up nicely with a Navigation property.
The code is currently:
var message = from m in soe.Messages.Include("ChildMessages")
where m.ID == id
&& m.IsActive
select m;
return message.FirstOrDefault();
What I really want is to only return 1 Message (that is equal to a particular ID and isActive) with all of its Active ChildMessages and I want to do it in one call to the database.
I have a solution for 4.0 (I'm not sure if it will work on 3.5, i hadn't check).
First, set your entities model Lazy Loading Enabled property to false. Note that as a result you will lose the references auto-loading.
Next, try this code:
var message = soe.Messages
.Where(m => (m.ID == id || m.ParentId == id) && m.IsActive)
.AsEnumerable()
.FirstOrDefault(e => e.Id == id);
The EF will resolve the parent-child references, and will not load other child references unless an explicit request will be made (like Include or Load). Notice that you must iterate over the Where results using AsEnumerable or otherwise they won't load.
I've concluded this is not possible in Entity framework.
A work around would be to return an anonymous type that satisfies the constraint. E.g.
var message = from m in soe.Messages
where m.ID == id
&& m.IsActive
select
new
{
Message = m,
ChildMessages = m.ChildMessages.Where(c => c.IsActive)
};
return message.FirstOrDefault()