Select * from Entities where Id = (select max(Id) from Entities) in Entity Framework

entity-framework

Question

I have an entity set called Entities which has a field Name and a field Version. I wish to return the object having the highest version for the selected Name.

SQL wise I'd go

Select * 
from table 
where name = 'name' and version = (select max(version)  
                                   from table 
                                   where name = 'name')

Or something similar. Not sure how to achieve that with EF. I'm trying to use CreateQuery<> with a textual representation of the query if that helps.

Thanks

EDIT: Here's a working version using two queries. Not what I want, seems very inefficient.

var container = new TheModelContainer();
var query = container.CreateQuery<SimpleEntity>(
    "SELECT VALUE i FROM SimpleEntities AS i WHERE i.Name = 'Test' ORDER BY i.Version desc");
var entity = query.Execute(MergeOption.OverwriteChanges).FirstOrDefault();
query =
    container.CreateQuery<SimpleEntity>(
        "SELECT VALUE i FROM SimpleEntities AS i WHERE i.Name = 'Test' AND i.Version =" + entity.Version);
var entity2 = query.Execute(MergeOption.OverwriteChanges);
Console.WriteLine(entity2.GetType().ToString());
1
4
12/5/2011 1:44:44 PM

Accepted Answer

Can you try something like this?

using(var container = new TheModelContainer())
{
    string maxEntityName = container.Entities.Max(e => e.Name);
    Entity maxEntity = container.Entities
                           .Where(e => e.Name == maxEntityName)
                           .FirstOrDefault();
}

That would select the maximum value for Name from the Entities set first, and then grab the entity from the entity set that matches that name.

7
12/5/2011 1:49:36 PM

Popular Answer

I think from a simplicity point of view, this should be same result but faster as does not require two round trips through EF to sql server, you always want to execute query as few times as possible for latency, as the Id field is primary key and indexed, should be performant

using(var db = new DataContext())
{
var maxEntity = db.Entities.OrderByDecending(x=>x.Id).FirstOrDefault()
}

Should be equivalent of sql query

SELECT TOP 1 * FROM Entities Order By id desc

so to include search term

string predicate = "name";

using(var db = new DataContext())
{
var maxEntity = db.Entities
.Where(x=>x.Name == predicate)
.OrderByDecending(x=>x.Id)
.FirstOrDefault()
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow