error 'Int32 ToInt32(System.String)' - asp.net-mvc-4

i have added follow action to get products accroding to cat.id.
[HttpPost]
public ActionResult OnlineHome(string CategoryId)
{
OnlineDataModel dm = new OnlineDataModel();
dm.CatagoryData = new List<category>();
dm.ProductData = new List<product>();
dm.CatagoryData = db.categories.ToList();
//dm.ProductData = (from p in db.products where p.CategoryID == Convert.ToInt32(CategoryId) select p).ToList() ;
var data= db.products.Where(d => d.CategoryID == Convert.ToInt32(CategoryId)).ToList();
return View(dm);
}
I am getting following error
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and >this method cannot be translated into a store expression.
need a solution for this.

Solution 1:
Try to declare you Integer variable first:
int iCategoryId = Convert.ToInt32(CategoryId);
Then update your code to:
var data= db.products.Where(d => d.CategoryID == iCategoryId).ToList();
Solution 2 (recommended):
Make sure your action receives an integer and modify the type of the variable:
public ActionResult OnlineHome(int CategoryId)
Then update your code the same way to:
var data = db.products.Where(d => d.CategoryID == CategoryId).ToList();
Feel free to add your own cast validations to both solutions.

Do like this.
int catId = Convert.ToInt32(CategoryId);
var data = db.products.Where(d => d.CategoryID == catId).ToList();

Related

Raven DB filter on subset of array items and sort on the cheapest of the filter results items

Assuming i have an parent class that I filter on various properties, one of which is a property that is an array of items .
Now say that i want to only return the parent item if my array of items as above a min value and below a max value ...that's fine i can work that bit out;
What if i then want to then sort on the filtered result set of those items
I made a c# fiddle example to show what im trying to achieve :
https://dotnetfiddle.net/mV4d28
(note that foo2 is returned first even though foo1 has items in its array that are less that those in foo2)
As i need to do this using a index i need the index to be able to compute the order by based on the filter criteria used in my query.
I know elasticsearch has an inner hits function that dose this and mongo has pipelines which also dose this so im sure Raven must have a way of doing this too ?
I was hoping using just index and a transform with prams i could achieve this so I tried it:
my index and transform look like this
public class familyTransfrom : AbstractTransformerCreationTask<ParentItem>
{
public class Result : ParentItem{
public double[] ChildItemValuesFiltered { get; set; }
}
public familyTransfrom(){
TransformResults = parents => from parent in parents
let filterMinValue = Convert.ToDouble(ParameterOrDefault("FilterMinValue", Convert.ToDouble(0)).Value<double>())
let filterMaxValue = Convert.ToDouble(ParameterOrDefault("FilterMaxValue", Convert.ToDouble(9999)).Value<double>())
select new Result{
ParentItemId = parent.ParentItemId,
ParentItemName = parent.ParentItemName,
ParentItemValue = parent.ParentItemValue,
//ChildItemValuesFiltered = parent.ChildItems.Where(p => p.ChildItemValues.Any(y => Convert.ToDouble(y) >= Convert.ToDouble(filterMinValue) && Convert.ToDouble(y) <= Convert.ToDouble(filterMaxValue))).SelectMany(t => t.ChildItemValues).ToArray<double>(),
ChildItemValuesFiltered = parent.ChildItems.SelectMany(p => p.ChildItemValues.Where(y => Convert.ToDouble(y) >= Convert.ToDouble(filterMinValue) && Convert.ToDouble(y) <= Convert.ToDouble(filterMaxValue))).ToArray<double>(),
ChildItems = Recurse(parent, x => x.ChildItems).Select(y => y).ToArray()
};
}
}
public class familyIndex : AbstractIndexCreationTask<ParentItem>{
public class Result : ParentItem {
public double[] ChildItemValues { get; set; }
}
public familyIndex(){
Map = parents => from parent in parents
select new Result{
ParentItemId = parent.ParentItemId,
ParentItemName = parent.ParentItemName,
ParentItemValue = parent.ParentItemValue,
ChildItemValues = parent.ChildItems.SelectMany(p => p.ChildItemValues.Select(y => y)).ToArray(),
ChildItems = Recurse(parent, x => x.ChildItems).Select(y => y).ToArray()
};
Index("ParentItemId", FieldIndexing.Analyzed);
Index("ParentItemName", FieldIndexing.Analyzed);
Index("ParentItemValue", FieldIndexing.Analyzed);
Index("ChildItemValues", FieldIndexing.Analyzed);
Index("ChildItems", FieldIndexing.Analyzed);
}
}
my query is as follows , (this is using the live raven playground so this should just work out of the box it you want to use it)
using (IDocumentStore store = new DocumentStore { Url = "http://live-test.ravendb.net/", DefaultDatabase = "altha" })
{
store.Initialize();
using (IDocumentSession session = store.OpenSession())
{
if(1 == 2){
//foreach (ParentItem element in data.OfType<ParentItem>()) {
// session.Store((ParentItem)element);
// session.SaveChanges();
//}
new familyIndex().Execute(store);
new familyTransfrom().Execute(store);
}else{
double filterMinValue = 3.0;
double filterMaxValue = 4.0;
var results = session
.Advanced
.DocumentQuery<familyIndex.Result,familyIndex>()
.WhereBetweenOrEqual("ChildItemValues", filterMinValue, filterMaxValue)
.SetResultTransformer<familyTransfrom, familyTransfrom.Result>()
.SetTransformerParameters(new Dictionary<string, RavenJToken> {
{ "FilterMinValue", filterMinValue },
{ "FilterMaxValue", filterMaxValue } })
.OrderBy("ChildItemValues")
.OfType<ParentItem>().ToList();
results.Dump();
}}
}
What i found was i cant use "ChildItemValuesFiltered" from the transform result as its not index. So unless i can order by the result of a transform ? i couldn't get this to work as although it filters it dosnt order correctly.
Is there another to achieve what i want using projections or intersection or rank or reduce try method ?
I was thinking if i had to perhaps i could use https://ravendb.net/docs/article-page/3.5/csharp/indexes/querying/sorting#custom-sorting
and do something like this:
public class SortByNumberOfCharactersFromEnd : IndexEntriesToComparablesGenerator
{
private readonly double filterMinValue;
private readonly double filterMinValue;
public SortByNumberOfCharactersFromEnd(IndexQuery indexQuery)
: base(indexQuery)
{
filterMinValue = IndexQuery.TransformerParameters["FilterMinValue"].Value<double>(); // using transformer parameters to pass the length explicitly
filterMaxValue = IndexQuery.TransformerParameters["FilterMaxValue"].Value<double>();
}
public override IComparable Generate(IndexReader reader, int doc)
{
var document = reader.Document(doc);
double[] childItemValues = (double[])document.GetValues("ChildItemValuesFiltered").Select(double.Parse).ToArray(); // this field is stored in index
return childItemValues.Where(x => x >= min && x <= max).Min();
}
}
then do a where filter and order by clause using index and transform passing in the same prams that i use in the where filter . however im not sure if this would work ?
More importantly im not sure how i go about getting the sort dll into the plugins ie what name space should the class go under, what name spaces dose it need to import, what assembly name dose it need to use etc
According to https://ravendb.net/docs/article-page/3.5/csharp/server/plugins/what-are-plugins i just need to drop the dll in and raven will this this up , however i cant seem to find what name space i need to reference for IndexEntriesToComparablesGenerator ?
im using linqpad 5 to test my stuff ...so in order to use the custom order i have to reference the class
any tips or advice or how to guild/examples welcome
so it didn't occur to me that i could do the filtering in the transform
TransformResults = parents => from parent in parents
let filterMinValue = Convert.ToDouble(ParameterOrDefault("FilterMinValue", Convert.ToDouble(0)).Value<double>())
let filterMaxValue = Convert.ToDouble(ParameterOrDefault("FilterMaxValue", Convert.ToDouble(9999)).Value<double>())
select new {
ParentItemId = parent.ParentItemId,
ParentItemName = parent.ParentItemName,
ParentItemValue = parent.ParentItemValue,
//ChildItemValuesFiltered = parent.ChildItems.Where(p => p.ChildItemValues.Any(y => Convert.ToDouble(y) >= Convert.ToDouble(filterMinValue) && Convert.ToDouble(y) <= Convert.ToDouble(filterMaxValue))).SelectMany(t => t.ChildItemValues).ToArray<double>(),
ChildItemValuesFiltered = parent.ChildItems.SelectMany(p => p.ChildItemValues.Where(y => Convert.ToDouble(y) >= Convert.ToDouble(filterMinValue) && Convert.ToDouble(y) <= Convert.ToDouble(filterMaxValue))).ToArray<double>(),
ChildItems = Recurse(parent, x => x.ChildItems).Select(y => y).ToArray()
} into r
where r.ChildItemValuesFiltered.Length > 0
orderby r.ChildItemValuesFiltered.Min()
select r;
This gives me what i wanted, here are the sample query:
http://live-test.ravendb.net/databases/altha/indexes/familyIndex?start=0&pageSize=25&resultsTransformer=familyTransfrom&tp-FilterMinValue=3&tp-FilterMaxValue=4
i cant take credit for this as guys at raven helped me but sharing the knowledge for others

How to run a count in Entity Framework

I have a Real Estate site with a Properties table and a PropertyImages table.
When the user uploads a picture, I want to run a query in the PropertyImages. then append that number to the picturename.
public IQueryable GetPictureCount()
{
int propertyId = Convert.ToInt16(ddlSelectProperty.SelectedValue);
var _db = new RESolution.Models.PropertyContext();
IQueryable query = _db.PropertyImages;
var mypic = (from c in _db.PropertyImages
where c.PropertyID == propertyId
select c).FirstOrDefault();
lblCount.Text = Convert.ToString(query);
}
I get this error: "Not all code paths return a value"
My environment is as follows:
VS Express 2013
Sql Express
win 8.1 development computer
when I change IQuaryable to "void" I get the error
'lblCount.text = query.Count().ToString();'
System.Linq.IQueryable does not contain a definition for 'Count' I have looked for a using directive but found non
I am still a little confused, though you guys are a god send.
Here is where I was able to get to work.
public void GetPictureCount()
{
lblfnameCheck.Text = ddlSelectProperty.SelectedValue;
int propertyId = Convert.ToInt32(lblfnameCheck.Text);
var _db = new RESolution.Models.PropertyContext();
var count = _db.PropertyImages.Count(t => t.PropertyID == propertyId);
lblCount.Text = Convert.ToString(count);
}
As dasblinkenlight mentioned, it seems that you do not want to return something, so make the method a void.
You probable want something like this:
public void GetPictureCount()
{
int propertyId = Convert.ToInt16(ddlSelectProperty.SelectedValue);
var _db = new RESolution.Models.PropertyContext();
IQueryable query = _db.PropertyImages;
var mypic = (from c in _db.PropertyImages
where c.PropertyID == propertyId
select c).FirstOrDefault();
var nrOfPics = Convert.ToString(query.Count());
lblCount.Text = nrOfPics;
mypic.name = mypic.name + nrOfPics; // I am guessing the name property
_db.SaveChanges();
}

get list of decision for a specific meetingtitle using linq asp.net

I have a database table. What I want is to get data using group by clause as I have used in below code.
Note that Decision is another table. now I want that all the decisions related to a specific Meeting Title should be shown in list.like
meetingtitle1=decision1,decison2,decison3
meetingtitle2=decision1,decison2
but below code returns only one decisiontitle.
public List<NewMeetings> GetAllMeetings()
{
var xyz = (from m in DB.MeetingAgenda
//join mp in Meeting on m.MeetingId equals mp.MeetingId
//where m.MeetingId == 2
group m by new { m.Meeting.MeetingTitle } into grp
select new NewMeetings
{
// meetingid = grp.Key.MeetingId,
meetingtitle = grp.Key.MeetingTitle,
decision = grp.Select(x => x.Decision.DecisionTitle).FirstOrDefault(),
total = grp.Count()
}).ToList();
List<NewMeetings> list = xyz.ToList();
return list;
}
public class NewMeetings
{
public int meetingid;
public string meetingtitle;
public string decision;
public int total;
}
Can somebody please tell me how to return a list of decisions to a specific Meetingtitle?
You are doing a FirstOrDefault on the list of decisions which obviously means you are only getting a single value. Instead you can join them all together into one longer string (separated by commas as you indicated in the question) by changing this line:
decision = grp.Select(x => x.Decision.DecisionTitle).FirstOrDefault(),
To this:
decision = string.Join(",", grp.Select(x => x.Decision.DecisionTitle)),
However, as the string.Join is not recognised by Linq to Entities, you need to do the string.Join after the data has been retrieved (i.e. after the ToList):
var xyz = (from m in DB.MeetingAgenda
group m by new { m.Meeting.MeetingTitle } into grp
select new
{
meetingtitle = grp.Key.MeetingTitle,
decisions = grp.Select(x => x.Decision.DecisionTitle),
total = grp.Count()
})
.ToList()
.Select(m => new NewMeetings
{
meetingtitle = m.meetingtitle,
decision = string.Join(",", m.decisions),
total = m.total
});

Linq to sql How to select elements from a list

I have two classes:
public class Artikel
{
int id{get;set;};
string name{get;set;};
}
public class NewArtikel
{
int id{get;set;};
List<Artikel> artikels{get;set;};
}
Now, I have a list of the second class
List<NewArtikel> myList = new List<NewArtikel>()
Is there are any posibility in LINQ to SQL to select all elements from myList with the needed Artikel.name
Yes
var allRequiredArtikels = myList.SelectMany(n => n.artikels)
.Where(a => a.name == "requiredName");
The SelectMany flattens all Artikels from all the NewArtikel elements, then the Where filters them by name.
Okay so, if you want the NewArtikels that have an Artikel with the required name you could do.
var newArtikels = myList.Where(n => n.artikels
.Any(a => a.name == "requiredName"));
List<NewArtikel> myFinalList = (from artikel in myList.artikels where artikel.name = "requiredName"
select new NewArtikel(){
Id= artikel.Id
}).ToList();

How do I append Skip and Take to an nHibernate IQueryOver

I want to do this:
NHibernate.IQueryOver<DataAccess.Domain.Product, DataAccess.Domain.Product> query = session.QueryOver<DataAccess.Domain.Product>();
query = query.Where(x => x.Name == "X");
query = query.Take(1).Skip(3);
List<Product> results = query.List().ToList();
I cant find any help on Skip or Take. The tooltip help (yes I'm that desperate) says that Skip and Take return IQueryOver but the error message says something to the effect "Cant implicitly convert IQueryOver{T} to IQueryOver{T,T}. I don't know what IQueryOver{T,T} is. I didn't ask for one of those anyway.
Try to change your code like this:
NHibernate.IQueryOver<DataAccess.Domain.Product> query = session.QueryOver<DataAccess.Domain.Product>();
query = query.Where(x => x.Name == "X");
query = query.Take(1).Skip(3);
var results = query.List();
Or, even better:
var results = session.QueryOver<DataAccess.Domain.Product>()
.Where(x => x.Name == "X")
.Take(1)
.Skip(3)
.List();
You can check my code here downloading NHibernateQueryOver.
UPDATE:
I think you're missing something. I would suggest you to read this article which has been really helpful for me.
In the paragraph about Associations they say:
An IQueryOver has two types of interest; the root type (the type of entity that the query returns), and the type of the 'current' entity
being queried. For example, the following query uses a join to create
a sub-QueryOver (analagous to creating sub-criteria in the ICriteria
API):
IQueryOver<Cat,Kitten> catQuery =
session.QueryOver<Cat>()
.JoinQueryOver(c => c.Kittens)
.Where(k => k.Name == "Tiddles");
The JoinQueryOver returns a new instance of the IQueryOver than has
its root at the Kittens collection. The default type for restrictions
is now Kitten (restricting on the name 'Tiddles' in the above
example), while calling .List() will return an IList. The type
IQueryOver inherits from IQueryOver.
This is what I do when I want to build multiple filter:
Domain.OrderAddress addressDestination = null;
Domain.Customer customer = null;
Domain.TermsConditionsOfSale termsConditionsOfSale = null;
ICriterion filter1 = Restrictions.Where<Domain.Order>(t => t.Company == "MYCOMPANY");
ICriterion filter2 = Restrictions.Where<Domain.Order>(t => t.WareHouseDelivery == "DEPXX");
ICriterion filter3 = Restrictions.Where<Domain.Order>(t => t.Status == "X");
ICriterion filter4 = Restrictions.Where(() => addressDestination.AddressType == "99");
ICriterion filter5 = Restrictions.Where(() => addressDestination.Province.IsIn(new string[] { "AA", "BB", "CC" }));
ICriterion filter6 = Restrictions.Where(() => termsConditionsOfSale.ReturnedGoodsCode != "01");
var ordersForProvinces = session.QueryOver<Domain.Order>()
.Inner.JoinAlias(t => t.OrderAddresses, () => addressDestination)
.Inner.JoinAlias(t => t.Customer, () => customer)
.Left.JoinAlias(t => t.TermsConditionsOfSale, () => termsConditionsOfSale);
ordersForProvinces
.Where(filter1)
.And(filter2)
.And(filter3)
.And(filter4)
.And(filter5)
.And(filter6);
var Results = ordersForProvinces.Skip(50).Take(20).List();
UPDATE-UPDATE:
NHibernate.IQueryOver<Domain.Person> person = session.QueryOver<Domain.Person>();
var myList = DoSomething(person);
Method:
private static IList<Domain.Person> DoSomething(NHibernate.IQueryOver<Domain.Person> persons)
{
ICriterion filter1 = Restrictions.Where<Domain.Person>(t => t.CompanyName.IsLike("Customer%"));
persons.RootCriteria.Add(filter1);
var x = persons.Skip(1).Take(3).List();
return (x);
}