Tip 36 – How to Construct by Query

While writing my tips series and writing EF controllers for MVC I found that I regularly wanted to create and attach a stub entity. Unfortunately it isn’t quite that simple, you have to make sure the entity isn’t already attached first, otherwise you’ll see some nasty exceptions. To avoid these exceptions I often found myself…

6

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 33 – How cascade delete really works in EF

Imagine that in your database you have a cascade delete on an FK relationship. Something like this: Here the Delete Rule says that when a Category is deleted all the related Products should be deleted too. If you generate an EF model from this database you get a model that on the surface looks no…

6

Wrapping Providers

For well over a year now I’ve been talking about how it is possible with EF to write a provider that sits between the EF and the native database provider. There are lots of reasons why you might do this. Here are some examples, you could write a: Tracing Provider Auditing Provider Caching Provider Query…

1

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

Tip 24 – How to get the ObjectContext from an Entity

Customers often ask how to get from an Entity back to the ObjectContext . Now generally we don’t recommend trying this. But sometimes you really need a way to get to the ObjectContext. For example if you are in method and all you have is the Entity, and you need the ObjectContext perhaps to do…

7

Ordering of Commands – What do you think?

Some of our customers write code like this: ctx.AddToCustomers(customer); ctx.AddToProducts(product1); ctx.AddToProducts(product2); And expect the Entity Framework to issue 3 insert commands in the same order. Today the EF doesn’t preserve this sort of ordering. Instead the order inserts/updates and deletes are made in the Entity Framework is based mainly on local inter-dependencies. For example if…

5