Ad-hoc SQL/POCO Queries in Entity Framework 4.0

Posted by on in Blogs
Since version 4.0, the Entity Framework has had the ability to query un-mapped data and project it onto POCOs using ad-hoc SQL.

Here, for example, is how we check the current SQL Server version:

        internal class SqlVersionInfo
public string Edition { get; set; }
public string ProductLevel { get; set; }
public string ProductVersion { get; set; }

private static SqlVersionInfo GetSqlServerVersion(ObjectContext context)
const string sql =
@"SELECT SERVERPROPERTY('productversion') as [ProductVersion],
SERVERPROPERTY('productlevel') as [ProductLevel],
SERVERPROPERTY('edition') as [Edition];";
var reader = context.ExecuteStoreQuery<SqlVersionInfo>(sql);
return reader.Single();

Note that no mapping step is required -- the code will just run with any ObjectContext at all.


Check out more tips and tricks in this development video: