Orders-EF-CodeFirst

MARCH 7, 2014 in WPF with 177 views and 65 downloads

(No Ratings Yet)

Orders demo application with Entity Framework using DbContext and Code-First

Built for Visual Studio 2010

Built for .NET 4.0

Orders-EF-CodeFirst

This sample shows how to use Entity Framework's Code-First programming model with SEF. It also demonstrates how to use DbContext (a simplified API new to Entity Framework 4.1) instead of ObjectContext.

This sample requires Entity Framework 4.1.

You can start with the Orders-POCO sample because Code-First is also using POCO classes. Delete the model file (.edmx) from your project, you won't need it, you will be creating your model in code.

Then write code for your context class (derived from DbContext; we chose to use DbContext for this sample, but you can do the same with ObjectContext if so desired, as in the Orders-EF-POCO sample) and write (or use, if they already exist) your own POCO entity classes (the classes are essentially the same as in the Orders-EF-POCO sample, except for a few additional attributes). In this sample, the object context class is the NORTHWNDEntities class in NORTHWNDEntities.cs, and the POCO classes are Customer, Order, Order_Detail, and Product classes in the same file NORTHWNDEntities.cs.

Note that (same as in the Orders-EF-POCO sample) the POCO classes inherit from the ObservableObject class (defined in the same file NORTHWNDEntities.cs). It is a simple class implementing INotifyPropertyChanged interface. This is an important requirement: Your classes need to be "observable", that is, to support property change notifications, implement INotifyPropertyChanged. Without that, data binding won't work as expected because changes you make in entities won't be reflected by bound controls. This is a general requirements for using POCO with data binding, not specific to SEF.

Note also that (same as in the Orders-EF-POCO sample) all properties of the POCO objects are virtual. That is necessary for the Entity Framework to create "proxies" with the POCO objects. Proxies, as well as observability, are needed for two-way data binding to work correctly (not only with SEF but in general with Entity Framework with POCO).

Working with DbContext (which is new to Entity Framework 4.1), you don't have the same design-time support as with ObjectContext. This minor inconvenience for users of Entity Entity Framework 4.1 will be removed in the next version of SEF. For now, if you want to use DbContext instead of ObjectContext, you need to work with C1DataSource control a little differently: instead of setting its ObjectContextType property at design time, set its ClientCache property in code. In this sample, we create ClientCache in code and put it in application resources (see App.xaml.cs) so it can be set in XAML like this: ClientCache="{StaticResource ClientCache}".

Tags