how to use LIMIT on DQL,
i have dql like this
$LampuOns = self::$em->createQuery("SELECT c FROM \Entities\Product\Category c WHERE id='{$Dataid}'")->execute();
when i added limit like this
$LampuOns = self::$em->createQuery("SELECT c FROM \Entities\Product\Category c WHERE id='{$Dataid}' LIMIT = 1")->execute();
it returned error message.
any have idea please?
DQL Don't implement any limit clausole, look at this for motivation.
So you must use the Doctrine Query::setMaxResults()
So somethings like:
$LampuOns = self::$em->createQuery("SELECT c FROM \Entities\Product\Category c WHERE id='{$Dataid}'");
$LampuOns->setMaxResult(1);
$LampuOns->execute();
Hope this help
Related
I have list with ids
List<int> listOfIds;
And I have a query with cars objects.
I would like to do something like this:
query = from e in query
join b listOfIdson e.b.Id equals b
select e;
but then I get error:
Specified method is not supported.
I know that its possible to do that by Join method which is avaiable on my query, but I have no idea how to do this. I can run following Join methods on my query:
query.Join()
query.JoinGroup()
Thats all
Thanks for help
Could you try with QueryOver ?
var results = session.QueryOver<Car>().AndRestrictionOn(x=> x.id).IsIn(listOfIds)
I am sort of new to this. Curious what happens in the following situation?
var q = //MY LINQ TO SQL QUERY.Select(...)
.........
.........
var c = q.Count();
.........
.........
var x = q.Where(....).Select(....);
var y = x.ToList();//or something such that forces materialization
var d = q.Count();//same as c
var e = x.Count();
var f = y.Count();
How many times did the sql statements make a trip to the db actually? Once at Count(). Again at Where()? Or Linq retains what it materialized during Count()?
Or it also depends on what the Where(..) has? Like if it is again referencing to database vs it just references what's obtained as part of 'q'/ or any other .net collections etc?
Edit:
Updated my code with a couple of other scenarios. Please correct my answers below:
q -no db trip
c -yes, but translates to aggregate qry - select Count(*) and not a result set (as per answer below)
x -no db trip. No matter what is written in the Where(..)
y - yes
d - yes - does not *reuse* c
e - yes - select count(*) EVEN THOUGH x already materized during y
f - no db trip
When you call Count it does not materialize the entire data set. Rather it prepares and executes a query like
SELECT COUNT(*) FROM ...
Using ExecuteScalar to get the result.
When you call Where and Select it does not materialize anything (assuming q is an IQueryable). Instead it's just preparing a query like
SELECT col1, col2, ... FROM ...
But it doesn't actually execute it at that point. It will only execute the query when you call GetEnumerator on q. You'll rarely do this directly, but anything like the following will cause your query to be executed:
var arry = q.ToArray();
var list = q.ToList();
foreach(var rec in q) ...
It will only execute this query once, so having multiple foreach loops will not create multiple database queries. Of course, if you create a new IQueryable based on q (e.g. var q2 = q.Where(...)) it will not be tied to the result set used by q, so it will have to query the database again.
I tested out your code in LINQPad, and it seems all your analyses are correct.
I am relatively new to LINQ and don't know how to do a Like condition. I have an IEnumerable list of myObject and want to do something like myObject.Description like 'Help%'. How can I accomplish this? Thanks
Look here:
http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/16/linq-to-sql-like-operator.aspx
Snippet:
StartsWith and Contains:
var query = from c in ctx.Customers
where c.City.StartsWith("L") && c.City.Contains("n")
select c;
And if you should use it with LINQ to SQL (does not work with LINQ to Objects):
Custom LIKE (System.Data.Linq.SqlClient.SqlMethods.Like):
var query = from c in ctx.Customers
where SqlMethods.Like(c.City, "L_n%")
select c;
You generally use the exact same syntax you'd use outside a query.
myObject.Description.StartsWith("Help")
Whether this actually works depends on where you're using LINQ (it might either be ran as code, in which case everything works, or get converted to something like else, such as SQL, which might have limitations), though, but it's always worth a try.
You can use StartsWith, EndsWith, or Contains depending where you want to check:
var result = from o in myCollection
where o.Description.StartsWith("Help")
select o;
You can optionally pass a StringComparison to specify whether to ignore case or not (for StartsWith and EndsWith) which would make the operation behave more like a SQL query:
var result =
from o in myCollection
where o.Description
.StartsWith("Help", StringComparison.InvariantCultureIgnoreCase))
select o;
If you want to do a case insensitive contains, you need to use IndexOf instead:
var result =
from o in myCollection
where o.Description
.IndexOf("Help", StringComparison.InvariantCultureIgnoreCase) > 0
select o;
you can use string.StartsWith or string.EndsWith or string.Contains property of string to use it as Like Operator.
Startswith will work for Like 'A%'
Endswith will work for Like '%A'
Contains will work like '%A%'
I'm trying to get Entity Framework to select an object and filter its collection at the same time. I have a JobSeries object which has a collection of jobs, what I need to do is select a jobseries by ID and filter all the jobs by SendDate but I can't believe how difficult this simple query is!
This is the basic query which works:
var q = from c in KnowledgeStoreEntities.JobSeries
.Include("Jobs.Company")
.Include("Jobs.Status")
.Include("Category")
.Include("Category1")
where c.Id == jobSeriesId
select c;
Any help would be appreciated, I've been trying to find something in google and what I want to do is here:http://blogs.msdn.com/bethmassi/archive/2009/07/16/filtering-entity-framework-collections-in-master-detail-forms.aspx
It's in VB.NET though and I couldn't convert it to C#.
EDIT: I've tried this now and it doesn't work!:
var q = from c in KnowledgeStoreEntities.JobSeries
.Include("Jobs")
.Include("Jobs.Company")
.Include("Jobs.Status")
.Include("Category")
.Include("Category1")
where (c.Id == jobSeriesId & c.Jobs.Any(J => J.ArtworkId == "13"))
select c;
Thanks
Dan
Include can introduce performance problems. Lazy loading is guaranteed to introduce performance problems. Projection is cheap and easy:
var q = from c in KnowledgeStoreEntities.JobSeries
where c.Id == jobSeriesId
select new
{
SeriesName = c.Name,
Jobs = from j in c.Jobs
where j.SendDate == sendDate
select new
{
Name = j.Name
}
CategoryName = c.Category.Name
};
Obviously, I'm guessing at the names. But note:
Filtering works.
SQL is much simpler.
No untyped strings anywhere.
You always get the data you need, without having to specify it in two places (Include and elsewhere).
No bandwith penalties for retrieving columns you don't need.
Free performance boost in EF 4.
The key is to think in LINQ, rather than in SQL or in materializing entire entities for no good reason as you would with older ORMs.
I've long given up on .Include() and implemented Lazy loading for Entity Framework
Seems like I may have missed something simple in the syntax, but I'd like to get the results of FirstOrDefault from a linq statement directly without having to store the IEnumerable in a temporary variable first. Something like this:
var bestCar = from c in cars
orderby c.Price
select first c
I know the first keyword doesn't actually exist but illustrates what I'd like to do. I also know I can wrap the from...select statement in parenthesis and call FirstOrDefault directly but I think the above syntax is cleaner and easier to read.
Enumerable.FirstOrDefault is one of the extension methods in the Enumerable class which does not have a corresponding LINQ syntax element. The only way to bind to this method is via method call syntax.
You can avoid the temporary by doing the follownig
var bestCar = (from c in cars
orderby c.Price
select c).FirstOrDefault();
There isn't a way to do that. LINQ is used for defining a query. Doing that doesn't actually cause an evaluation, whereas executing FirstOrDefault (or enumerating over it) executes the query.
var bestCar = (from c in cars
orderby c.Price
select c).FirstOrDefault()
OR
var bestCar = cars.OrderBy(c => c.Price).FirstOrDefault()
var bestCar = (from c in cars
orderby c.Price
select c).FirstOrDefault();
Sorry I didn't read your question entirely, it seems that this may be exactly what you don't want to do.
In VB you can use 'Aggregate':
Dim BestCar = Aggregate c In cars
Order By c.Price
Into FirstOrDefault