Implicit "Magic" Casting
Simple.Data allows you to implicitly cast query results into a static object type or collection of objects, rather than use boxing or the ‘as’ keyword. It does this by overriding the dynamic object’s TryConvert method to perform the case implicitly. Any matching properties between dynamic object and static type are auto-mapped.
Note that you can’t currently map types which aren’t straight maps to database types. For instance, from char to byte or string to byte[]. Issue 50 covers this issue.
SimpleRecords To Single Objects
In the code below, album is returned as a dynamic object, created as a SimpleRecord instance, and will return values for all the Album fields in the table.
var album = db.Albums.FindByGenreId(1);
You can implicitly cast this into an Album object with the following code.
Album album = db.Albums.FindByGenreId(1);
Note that if the implicit cast fails, album will be set to null, so you may want to use the null coalescing operator to cater for that case. For example
Album album = db.Albums.FindByGenreId(1) ?? new Album();
Simple.Data also provides the LINQ-like operator Cast<T>() to make an explicit cast.
SimpleQueries to Object Collections
In this code, a list of albums is returned as IEnumerable<dynamic>, created as a SimpleQuery instance.
var albums = db.Albums.FindAllByGenreId(1);
You can magic cast this to IEnumerable<Album> or indeed any collection type of Album implementing IEnumerable.
IEnumerable<Album> = db.Albums.FindAllByGenreId(1); List<Album> = db.Albums.FindAllByGenreId(1); Array<Album> = db.Albums.FindAllByGenreId(1);
Again, should the implicit cast fail, albums will be set to null, so you may want to use the null coalescing operator to cater for that case. For example
List<Album> = db.Albums.FindAllByGenreId(1) ?? new List<Album>();
Simple.Data also provides the LINQ-like operators Cast<>()
, ToList<T>()
and ToArray<T>()
to make an explicit cast.
Casting to The Wrong Type
Make sure you know how many results you are expecting to receive from your Simple.Data query before making an implicit cast.
All
,FindAll
, andFindAllBy
all return multiple objects as a SimpleQuery. Attempting to cast a SimpleQuery into a single object will result in a RuntimeBinderException being thrown.Find
,FindBy
andGet
all return single objects as a SimpleRecord. Attempting to cast a SimpleRecord into a collection of objects will result in a RuntimeBinderException being thrown.