Why does this work:
var ret = Session.Query<ListingEvent>()
.TransformWith<ListingEventProfileTransformer, ListingEventDto>()
.ToList();
var ret2 = ret.Where(x => x.EventInstance.Slug == slug);
return ret2;
but this does not:
var ret = Session.Query<ListingEvent>()
.TransformWith<ListingEventProfileTransformer, ListingEventDto>()
.Where(x => x.EventInstance.Slug == slug);
return ret;
Obviously the 1st one is no good as it needs to enumerate the collection before adding my predicate.
Surely they should both work?!
The second query is still at an IQueryable, so nothing is executed until you force the results to come back. Try this:
var ret = Session.Query<ListingEvent>()
.TransformWith<ListingEventProfileTransformer, ListingEventDto>()
.Where(x => x.EventInstance.Slug == slug)
.ToList(); // Force the results to come back
return ret;
Related
I'm using .net Core 6 web API, and I've this case where I need to loop through multiple object, and each has a IQueryable result.
Then all results need to be grouped in one query. Finally the the result will be sent as paginated list.
Here's more details in the code, I will get list of ObjectA from db:
var query = _context.ObjectA.AsQueryable();
Now I need to get list of User. For some reason the users will have multiple records with their username, so each record represent a role:
var rolesFromDb = await _context.User.Include(x => x.Role).Where(x => x.Username == "user").ToListAsync();
Now I need to loop through dynamic roles and filter the query. I have 2 (or more) conditions, the the code will look like this:
if (rolesFromDb.Count != 0)
{
var result = new List<ObjectA>();
foreach (var item in rolesFromDb)
{
if (item.Role.Level == 1)
{
var condition1 = query.Where(x => x.Level == 1);
result.AddRange(condition1);
continue;
}
if (item.Role.Level == 2)
{
var condition2 = query.Where(x => x.Level == 2);
result.AddRange(condition2);
continue;
}
}
query = result; // I need to do something like this, this is not the way to do ofc
}
After this loop, I've a search filter that depends on this query.
In general, my main issue is I'm not able to make query = all filtered queries.
Thank you.
in store procedure we can check record is exist or not using following query for fast performance
if EXISTS ( Select 1 from Table_Name where id=#id )
But what about Linq query.
right now i have to store whole data in object like this
UserDetail _U=db.UserDetails.where(x=>x.id==1).FirstOrDefault();
Any Solution?
Use Linq's Any ie bool exist = db.UserDetails.Any(x => x.id == 1);
if(db.UserDetails.Any(x => x.id == 1)) {
var userDetail = db.UserDetails.FirstOrDefault(x => x.id == 1);
}
bool exist = db.UserDetails.Where(x=>x.id==1).Any();
if(exist){
//your-code
}else{
//your-code
}
Just check
if(_U == null)
This way you will get what you want in single query and you not need to execute addition query like
db.UserDetails.Any(x => x.id == 1)
I think, it does not require to fire two query. It can be accomplish by single query.
UserDetails objUserDetails =db.UserDetails.FirstOrDefault(x => x.id == 1);
if(objUserDetails==null)
{
// Do something
}
else
{
// do something with objUserDetails
}
var qry = db.User_Detail.Where(x => x.User_Id == 1).FirstOrDefault();
if(qry !=null)
{
// Do something
}
else
{
return false;
}
Try This...
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();
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);
}
I'm using the QueryOver api that is part of NHibernate 3.x. I would like to get a row count, but the method I'm using returns all objects and then gets the count of the collection. Is there a way to just return an integer/long value of the number of rows?
I'm currently using:
_session.QueryOver<MyObject>().Future().Count()
After a bit of playing around with the api, this will do it:
_session.QueryOver<MyObject>()
.Select(Projections.RowCount())
.FutureValue<int>()
.Value
If you don't want to return it as a future, you can just get the SingleOrDefault<int>() instead.
Another method
var count = Session.QueryOver<Employer>()
.Where(x => x.EmployerIsActive)
.RowCount();
Another method:
int employerCount = session
.QueryOver<Employer>()
.Where(x => x.EmployerIsActive) // some condition if needed
.Select(Projections.Count<Employer>(x => x.EmployerId))
.SingleOrDefault<int>();
Im using like this:
public int QuantidadeTitulosEmAtraso(Sacado s)
{
TituloDesconto titulo = null;
Sacado sacado = null;
var titulos =
_session
.QueryOver<TituloDesconto>(() => titulo)
.JoinAlias(() => titulo.Sacado, () => sacado)
.Where(() => sacado.Id == s.Id)
.Where(() => titulo.Vencimento <= DateTime.Today)
.RowCount();
}