Please help I am getting the following error when I am binding the drop down list in the form
Unable to cast object of type 'System.Data.Objects.ObjectQuery1[<>f__AnonymousType02[System.String,System.Int32]]' to type 'System.Collections.Generic.List`1
I have written the query in Linq language
return (IList )(from p in db.tbl_PRODUCT_CATEGORY
select new
{
catname = p.category_name,
catid = p.category_id,
});
I don't know whether it is correct
Please give me the correct format of the query
I think your query should look more like this:
return (IList)(from p in db.tbl_PRODUCT_CATEGORY select new { catname = p.category_name, catid = p.category_id, }).ToList();
Related
private void BindGrid()
{
AdvContextEF db = new AdvContextEF();
var query = from r in db.mytable
orderby r.CreateDate descending
select new
{
r.id,
r.code,
r.mytable.relatedtables[0].TheCenter.Name
};
RadGrid1.DataSource = query.ToList();
RadGrid1.DataBind();
}
I got the following error when running the code above.
LINQ to Entities does not recognize the method 'AdvContextEF.mymethod get_Item(Int32)' method, and this method cannot be translated into a store expression.
thank you
Instead of trying to index into r.mytable.relatedtables[0], try using .FirstOrDefault().
r.mytable.relatedtables.FirstOrDefault().TheCenter.Name
or
Name = r.mytable.relatedtables.Select(rt => rt.TheCenter.Name).FirstOrDefault()
I need to return a number of Linq query results into a List object based on a foreign key value. What is the syntax for doing this? I am new to using Linq, so below is my best guess so far. I receive an error in the .Where() "clause" stating "The name 'pt' does not exist in the current context. Any help would be greatly appreciated!
List<AgentProductTraining> productTraining = new List<AgentProductTraining>();
var prodCodes = productTraining.Select(pt => new[]
{
pt.ProductCode,
pt.NoteId,
pt.ControlId
})
.Where(pt.CourseCode == course.CourseCode);
You would need to switch the locations of where and select if you're using extension methods:
var prodCodes = productTraining.Where(pt => pt.CourseCode == course.CourseCode)
.Select(pt => new SomeRandomType
{
ProductCode = pt.ProductCode,
NoteId = pt.NoteId,
ControlId = pt.ControlId
});
I also recommend, as you can see above, that you create a type for that select statement so that you're not relying on anonymous types. You should put in into an object type that you know everything about.
Also, if CourseCode is a string, that should be pt.CourseCode.Equals(course.CourseCode).
I have one SelectListItem for DropDownList. I have to filter based on some condition. If I try adding the condition then its gives me an error like this (LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression). I ll be adding that code here. Please guide me to solve this.
Code
IEnumerable<SelectListItem> IssueId = (from txt in Db.Issues where txt.BibId == BibId
select new SelectListItem()
{
Text = txt.Description,
Value = txt.Id.ToString(),
Selected = true,
});
SelectList IssueIds = new SelectList(IssueId, "Value", "Text");
ViewBag.IssueId = IssueIds;
Thanks
Try this:
LINQ2EF does not know ToString() but after AsEnumerable() you'll get a local collection when ToString() is implemented.
IEnumerable<SelectListItem> IssueId =
(from txt in Db.Issues.Where(e => e.BibId == BibId).AsEnumerable()
select new SelectListItem()
{
Text = txt.Description,
Value = txt.Id.ToString(),
Selected = true
});
Linq To Sql can't generate TSQL for txt.Id.ToString()
You will need to iterate the result instead after executing the query, or cast to Enumerable as xeondev suggests.
That extension does not seem to be sorted by linq to Entities but you could just do the mapping once you have the issues, e.g.
var issues = (from issue in Db.Issues
where issue .BibId == BibId
select issue ).ToList();
IEnumerable<SelectListItem> IssueId = (from txt in issues
where txt.BibId == BibId
select new SelectListItem()
{
Text = txt.Description,
Value = txt.Id.ToString(),
Selected = true,
});
I currently have a LINQ query written in one my controllers that I want to return a single blog post (based off a model) with corresponding comments and topics.
This is what I currently have as my query which I used to return a list of all my blog posts for the home page. I added "where p.id == id (which is the parameter taken in by the ActionResult to fetch the correct post.
var post = from p in db.Set<BlogPost>()
where p.id == id
select new PostViewModel
{
Id = p.id,
Title = p.Title,
DateCreated = p.DateCreated,
Content = p.Content,
Topics = p.Topics,
Comments = p.Comments,
CommentCount = p.Comments.Count
};
return View(post);
The return currently is sending an IQueryable when I just want it to be a single post. Currently I have a foreach in my razor view which is useless and wrong but it works. How can I change this to do what I want?
You can do:
return View(post.SingleOrDefault());
Or if you want to have an exception in the case list is empty:
return View(post.Single());
Just add First() or Single() (which one is right for you depends on context) to your query:
return View(post.First());
It sound like you want to use First or Single:
return View(post.Single());
The difference between them is that Single will throw an exception if more than one matching row is found.
Just do post.First() that should do the trick. Really any function that produces a concrete value will work. First, FirstOrDefault, Single, SingleOrDefault, ToList, or ToArray
I have included the links to each method so you can see what works for you. It sounds like you will want a First or Single variation, depending on if you want errors if more than one post is pulled
replace your LINQ with this
var post = (from p in db.Set<BlogPost>()
where p.id == id
select new PostViewModel
{
Id = p.id,
Title = p.Title,
DateCreated = p.DateCreated,
Content = p.Content,
Topics = p.Topics,
Comments = p.Comments,
CommentCount = p.Comments.Count
}).FirstOrDefault();
how come this work
public IQueryable<Category> getCategories(int postId)
{
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
var query = from c in categories.GetAll()
join pcm in postCategoryMap.GetAll() on c.CategoryId equals pcm.CategoryId
where pcm.PostId == 1
select new Category
{
Name = c.Name,
CategoryId = c.CategoryId
};
return query;
}
but this does not
public IQueryable<Category> getCategories(int postId)
{
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
var query = from c in categories.GetAll()
join pcm in postCategoryMap.GetAll() on c.CategoryId equals pcm.CategoryId
where pcm.PostId == postId
select new Category
{
Name = c.Name,
CategoryId = c.CategoryId
};
return query;
}
The issue is most likely in the implementation of the query provider.
pcm.PostId == 1
and
pcm.PostId == postId
actually have a big difference. In the expression tree the first is generated as a ConstantExpression which doesnt need to be evaulated.
With the second, the compiler actually generates an inner class here (this is the _DisplayClassX that you see). This class will have a property (will most likely be the same name as your parameter) and the expression tree will create a MemberAccessExpression which points to the auto-generated DisplayClassX. When you query provider comes accross this you need to Compile() the Lambda expression and evaluate the delegate to get the value to use in your query.
Hope this helps.
cosullivan
The problem is not the linq itself,
you need to be sure that the context or provider object is able to fetch the data.
try testing the
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
objects and see if they are populated or if they behaving as required.
you may want to search the generated code for c__DisplayClass1 and see what you can see there. some times the generated code dose some weird things.
when you step into you code check the locals and the variable values. this may also give you some clues.
Edit : Have you tried to return a List<> collection ? or an Enumerable type?
Edit : What is the real type of the item and query may not be iterable