Tip 35 – How to write OfTypeOnly<TEntity>()

If you write a LINQ to Entities query like this: var results = from c in ctx.Vehicles.OfType<Car>()               select c; It will bring back, Cars and any type that derives from Car, like say SportCar or SUV. If you just want Cars and you don’t want derived types like SportCars or SUVs in LINQ to…

4

Tip 30 – How to use a custom database function

Imagine you have a database function like the DistanceBetween function in Nerd Dinner: CREATE FUNCTION [dbo].[DistanceBetween](   @Lat1 as real,   @Long1 as real,   @Lat2 as real,   @Long2 as real)RETURNS realASBEGIN…END And you want to use it with the Entity Framework. Declaring the Function The first step is to open your EDMX file in the XML editor…

11

Tip 25 – How to Get Entities by key the easy way

Sometimes rather than writing this: var customer = ctx.Customers.First(c => c.ID == 5); You would rather write something like this: var customer = ctx.Customers.GetCustomerById(5); In .NET 4.0 this would be trivial to do by modifying the T4 templates that do code gen. You would simply produce an extension method for each EntityType, something like this:…

5

DefiningQuery versus QueryView

The Entity Framework is a flexible beast. So much so that it provides not one but two ways to create views over the database. DefiningQueries live in the storage schema file, or ssdl, and are written in the native SQL of the database engine being used, i.e. T-SQL for SqlServer. QueryViews on the other hand…

2