Above we’ve defined two POCO classes - “Product” and “Category” – that we’ll use to represent the “Products” and “Categories” tables within our Northwind database.
In today’s blog post I’m going to cover a question that several people asked me recently, which is: “how do I use EF code-first with an existing database?
” EF “Code First” works great with existing databases, and enables a very nice code-centric development approach with them. Note that all of the EF concepts are identical regardless of whichever type of ASP. We’ll use “File-New Project” within VS 2010 (or the free Visual Web Developer 2010 Express) and choose the “ASP.
In particular, it enables you to use clean “plain old classes” (aka POCO) for your model objects, and cleanly map them to/from the database using either the default mapping conventions or by overriding them with custom schema mapping rules. My previous two EF “code first” blog posts used ASP. NET Web application” project template to create the new application. NET Web Application” project in VS 2010 is a nice starter template that provides a default master-page layout with CSS design (I blogged about this new starter project template in a previous blog post).
What this means is that if you retrieve a Product entity, its Category information will not be retrieved from the database until you access its Category property (or unless you explicitly indicate that the Category data should be retrieved when you write your LINQ query to retrieve the Product object).
Once we’ve created our “Product” and “Category” POCO classes, we used EF “code first” to create a “context” class that we can use to map our POCO model classes to/from tables within the database: The “Northwind” class above is the context class we are using to map our Product and Category classes to/from the database.