ToScalar
ToScalar
and ToScalar<T>
return a property from the results of a query as a scalar value. ToScalar
returns the value as its default type. ToScalar<T>
allows you to determine the type the value will be cast to. Both methods work against SimpleRecord and SimpleQuery types, but with slightly different rules.
SimpleRecords
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.Get(1);
Calling ToScalar
on this will return the first property in the SimpleRecord as a scalar value. In this case, it will return the AlbumId property as an int
. Calling ToScalar<T>
allows you to cast that scalar value into another type.
int AlbumId = db.Albums.Get(1).ToScalar();
If you include a Select
method in your query, ToScalar
will return the first field identified in that method. For example, the following code will return the Title field as a string.
string Title = db.Albums.Select(db.Albums.Title).Get(1).ToScalar();
Exceptions
ToScalar
andToScalar<T>
will throw aRuntimeBinderException
if the query you apply them to returns no rows (null).ToScalar<T>
will throw anInvalidCastException
if the value you are targetting cannot be cast to type T.
SimpleQueries
ToScalar
and ToScalar<T>
may only be applied to SimpleQueries that contain one result. For example
var albums = db.Albums.FindAllByGenreId(1).FirstOrDefault();
As with SimpleRecords, calling ToScalar
on this will return the first property in the first SimpleRecord result as a scalar value. Calling ToScalar<T>
allows you to cast that scalar value into another type. In this case, it will return the AlbumId property as an int
.
int AlbumId = db.Albums.FindAllByGenreId(1).FirstOrDefault().ToScalar();
If you include a Select
method in your query, ToScalar
will return the first field identified in that method. For example, the following code will return the Title field as a string.
string Title = db.Albums.FindAllByGenreId(1).Select(db.Albums.Title).FirstOrDefault().ToScalar();
Exceptions
ToScalar
andToScalar<T>
will throw aSimpleDataException
if the query you apply them to returns no rows (i.e. is null) or returns more than one rowToScalar<T>
will throw anInvalidCastException
if the value you are targetting cannot be cast to type T.