Home > C#, Magiq > Magiq: Querying a collection

Magiq: Querying a collection

One of the future features of Magiq will be mass operations to collections. I mean that

var country = CountryRepository.GetById(1);
country.Cities.Where( x => x.Population > 100000 ).Set( x => x.IsBigCity, true ).Update();

should generate a t-sql like

UPDATE [t0] SET [t0].IsBigCity = @p2 FROM Cities [t0] where [t0].Population > @p1 AND [t0].CountryId = @p2

Of course, this should be possible only if the collection is a Lazy one, so all the information needed is inside of it (it’s the same information needed to retrieve the items). For Linq-to-sql is EntitySet. For NHibernate, AbstractPersistentCollection (PersistentGenericBag, PersistentGenericList, PersistentGenericSet and PersistentGenericMap).

The problem (because there’re always problems) is that those classes doesn’t implement IQueryable and the previous magiq statement will work always as magiq-to-objects, because the collection is enumerated once the Where extension method is called and the Set method is called to a simple IEnumerable.

Talking with Sebas and my friend Jonas, we conclude that the best way to solve this is adding an extension method ToQueryable that converts the lazy enumerable to a queryable one (I would like to call it “AsQueryable”, but it already exists :S). I know, it’s a workaroud, but… it seem like I have no choice.

So, the API will look like:

var country = CountryRepository.GetById(1);
country.Cities.ToQueryable().Where( x => x.Population > 100000 ).Set( x => x.IsBigCity, true ).Update();

The great news is that you can use it for sub selecting collections. It would be the same feature that nhibernate has, but for all the orm’s that have lazy collections (of course, nhibernate magiq provider will implement this feature using it own feature).

Something like:

var country = CountryRepository.GetById(1);
country.Cities.ToQueryable().Where( x => x.Population > 100000 );

will execute

SELECT [t0].Id, [t0].Population, [t0].Name FROM Cities [t0] where [t0].Population > @p1 AND [t0].CountryId = @p2

Isn’t it pretty?

Advertisements
  1. No comments yet.
  1. February 19, 2010 at 11:04 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: