EF Code First and Data Scaffolding with the ASP.NET MVC 3 Tools Update

Earlier this week I blogged about the new ASP.NET MVC 3 Tools Update that we shipped last month. 

In today’s blog post I’m going to go into more detail about two of the cool new features it brings:

  1. Built-in support for EF 4.1 (which includes the new EF “code-first” support)
  2. Built-in data scaffolding support within Visual Studio (which enables you to rapidly create data-driven sites)

These two features provide a really sweet, and extremely powerful, way to work with data and build data-driven web applications.

Scenario We’ll Build

To help illustrate how to use the above features, we’ll walkthrough building a simple data-drive site.  It will support listing products:

SNAGHTML4e066438

As well as creating/editing new products (and categories):

SNAGHTML4e078291

We can now build this entire application (and create the database that backs it) with ASP.NET MVC 3 in only a minute or two.

Step 1: Create New Project

We’ll begin by creating a new ASP.NET MVC 3 project (using the File->New Project menu command).  We’ll use the “Internet Project” template – which will provide us with a default starter template for our application. 

When you look at the newly created project within the Solution Explorer, you’ll see that the ASP.NET MVC 3 Tools update adds a new assembly – EntityFramework – to our ASP.NET MVC 3 projects:

image

The EntityFramework assembly implements Entity Framework 4.1 – which we also released last month.  EF 4.1 brings with it a bunch of great data API improvements to .NET – including the new “code first” option.  EF Code First provides a really elegant and clean way to work with data, and enables you to do so without requiring a designer or XML mapping file.  You can now easily take advantage of this by default with all new ASP.NET MVC 3 projects.

We’ll be using the EF Code First approach to implement our data access for this application.

Step 2: Implement Model Classes

Our first step will be to create two classes – Product and Category – that we’ll use to define the “model” of our application.  We’ll implement these as standard “plain old C# objects” within the \Models folder of our project using the code below:

image

Notice how the above classes are just standard classes with .NET data-types.  They do not need to derive from any base class, nor implement any interfaces. 

In addition to standard scalar properties, each class has an “association” property.  For example, the “Product” class has a “Category” property that enables a developer to get access to the Category it belongs to.  Likewise the “Category” class has a “Products” property that enables a developer to retrieve the Products that are within that particular Category.  EF Code First can handle automatically managing these associations (using the Primary Key/Foreign Key values), and can lazy load the appropriate data on-demand.

Step 3: Implement a StoreContext Class using EF Code First

Now that we’ve defined our two model classes, our next step will be to implement a “DbContext” class using EF code First that will map the model classes to tables in a database.  We’ll implement this using the code below:

SNAGHTML4d35a6ee

The “StoreContext” class above is the DbContext class we are using to map our Product and Category classes to/from a database.  It derives from the DbContext base class provided by EF Code First, and exposes two properties that correspond to tables within our database.  For this sample we are using the default “convention over configuration” based mapping rules to define how the classes should map to/from the database.  This means that the Products property will map to a Products table, and the Categories property will map to a Categories table.  In later blog posts I’ll talk about how you can optionally override this and perform custom mappings.

You can add the above class anywhere within your solution.  For example, you could add it within the \Models folder of your project – or within a separate class library project if you prefer to keep your data code separate.  You’ll want to add a “using” statement to the System.Data.Entity namespace at the top of the class file (in order to reference the DbContext and DbSet<T> classes).

After you’ve saved the above class files, compile the project – you’ll want to have built it before the next step.

Step 4: Scaffold a Categories Controller

We have everything we need to model our data and save/retrieve it from a database.  Now let’s create an ASP.NET MVC Controller class that will implement the support necessary to display our Category data and enable creating/editing/deleting Category objects.  Prior to last month’s ASP.NET MVC 3 Tools Update, you would have had to manually write a Controller class to do this (and implement all of the EF data access code yourself).  The ASP.NET MVC 3 Tools Update now includes built-in “scaffolding” support that can help do this for you automatically.

To scaffold a new Categories controller class, we’ll right-click on the “/Controllers” folder of our project and choose the Add->Controller context menu:

image

Selecting Add->Controller will bring up the “Add Controller” dialog.  We’ll name the controller class we want to create “CategoriesController”.  Starting with last month’s ASP.NET MVC 3 Tools Update, the “Add Controller” dialog also now supports a new “Scaffolding options” section – which enables you to choose to “scaffold” the new controller using a variety of built-in templates:

image

We’ll choose the “Controller with read/write actions and views, using Entity Framework” template – which will create a Controller class that has all of the EF code necessary to create, update, list and delete model objects.

After selecting this template, we can choose the model class we want our Controller to implement CRUD support for – in this case the “Category” class.  We can also select the EF DbContext/ObjectContext class that we want to use to access the database – in this case the “StoreContext” class we defined earlier:

SNAGHTML4d81d687

When we click the “Add” button, Visual Studio will automatically create a CategoriesController class for us – with appropriate Create, Edit, Details, Delete and Index action methods inside it – as well associated view templates for each of the actions:

image

If you open the CategoriesController.cs class you’ll find that the action methods within it implement the EF data access code necessary for CRUD support:

image

And now we have all of the code we need to implement data listing/editing for Categories within our database

Step 5: Configuring our Database Location

The last step we’ll do before running our application is to point our application at the database we want to use.  EF code first allows you to use an existing database you already have defined, or alternatively you can point it at a database that doesn’t yet exist – in which case it will automatically create it for you using the model classes you’ve defined.

No Connection-String

By default, you actually don’t need to configure a connection-string to point at a database.  If you don’t specify one, EF Code-First will by default create a new SQL Express database whose name matches your DbContext class name (for example: above it would create a ScaffoldingDemo.Models.StoreContext database within your local .\SQLExpress database instance). 

Explicitly Specifying a Connection-String

You can alternatively explicitly specify where you want your database to live by adding a connection-string to your application’s web.config file.  You’ll want the name of the connection-string to match the DbContext class name.  For example – in our application above our DbContext class was named “StoreContext”, and so by default EF will look for a connection-string with the same name to determine the database location.

Below is the entry we’d add to our web.config file if we wanted to use an embedded SQL CE database named “Store.sdf” within our application’s \App_data folder:

<configuration>
      <connectionStrings>
              <add name="StoreContext"
                         connectionString="Data Source=|DataDirectory|\Store.sdf"
                         providerName="System.Data.SqlServerCe.4.0" />
       </connectionStrings>

</configuration>

You can learn more about SQL CE – and the new VS 2010 SP1 tooling support for it – from my previous blog post about it.

Step 6: Run the Application

Ok – let’s now run the application and navigate to the /Categories URL.  This will execute our CategoriesController’s Index() method – which will list all categories in our database.  Currently we don’t have any:

SNAGHTML4dede162

Let’s click the “Create New” link to create a new category – this will navigate to the /Categories/Create URL, which provides us with a form to create a new category:

SNAGHTML4def03ef

Clicking the “Create” button will post the form to our CategoriesController and add a new Category to our database.  We can repeat this a few times to add several different categories:

SNAGHTML4df02093

The cool thing is that we didn’t have to write any Controller or View code to enable this – the scaffolding support automatically generated the code we needed to enable this.  This provides a really easy way to get started.  We can then go in and tweak it as necessary to customize the functionality further.

Step 7: Looking at the database

We configured our application to use a connection-string that pointed to a SQL CE database that (at the time) didn’t exist.  When we ran our application, EF 4.1 detected that the database didn’t exist and automatically created it for us – based on the Product and Category classes we defined earlier. 

To see the database, click the “Show All Files” icon at the top of Visual Studio’s “Solution Explorer” and add the “Store.sdf” database that was automatically created by EF to your project:

image

You can then double-click the database to open it up in the Server Explorer – and expand the tables within it to see the schema that was created:

image

Notice above how EF Code First automatically created the appropriate database schema based on the Category and Product classes we created earlier.  It also automatically setup Primary Key/Foreign-Key relationships between the two tables based on the association properties specified in the classes.

Step 8: Scaffolding a Products Controller

We’ve created a CategoriesController class to manage listing and editing Categories.  Let’s now create a ProductsController class to manage listing and editing Products.

Just like before, we’ll right-click on the \Controllers folder in our project and choose the Add->Controller context menu.  We’ll name the Controller class we want to create “ProductsController” and indicate that we want to scaffold using the EF template with a Product model class:

SNAGHTML4dfb7c0b

Clicking the “Add” button will scaffold a ProductsController class for us, with appropriate action methods for CRUD scenarios, and create the associated view templates that go with them:

image

We can then run our project again and navigate to the /Products URL within it:

SNAGHTML4dfeca88

Let’s click the “Create New” link to create a new Product:

SNAGHTML4e028a2f

One cool thing to notice is that the “Category” is a drop-down of valid Categories (and not just a textbox with a foreign-key integer value):

image

The scaffolding support within Visual Studio was smart enough to detect that Category was an association, and scaffold EF code that populates the drop-down with valid Categories.

After entering several products our /Products URL will display the data like below:

SNAGHTML4e066438

Notice again how Category is displayed using the friendly name – and not just the foreign-key value.

Learning More

The above walkthrough provided a quick look at the new EF code-first and data scaffolding support built-into the ASP.NET MVC 3 Tools Update, and how you can use them to easily and quickly jumpstart application development.  EF Code First enables you to write incredibly clean data access code.  The data scaffolding support enables you to rapidly create data UI – and then allows you to go in and easily tweak/customize it further.

In addition to working with EF Code-First, you can also use the data scaffolding support against standard EF ObjectContext objects (built using either the database-first or model-first approach and the EF WYSIWYG designer).

Scaffolding

You can learn more about the new ASP.NET MVC 3 Scaffolding Support from Steve Sanderson’s excellent talk about it at MIX:

In his talk Steve also covers how you can use the scaffolding support from the command-line (using NuGet) as well as how you can download and use additional scaffolding templates (for example: ones that can automatically implement a repository pattern, etc).  Also make sure you bookmark Steve’s excellent blog series about scaffolding (and its extensibility) here:

EF Code First

I’ll be doing more blog posts about EF Code First in the future.  Below are links to some tutorials I’ve written in the past about it:

Note: The above tutorials were written against the CTP4 release of EF Code First (and so some APIs are a little different) – but the concepts and scenarios outlined in them are the same as with the final release.

ASP.NET MVC 3

If you want to learn more about ASP.NET MVC 3, I highly recommend Scott Hanselman’s excellent video presentations at the Dutch DevDays and at MIX:

Also check out all of the new content and videos on the http://asp.net/mvc web-site:

Summary

The new ASP.NET MVC 3 Tooling Update is full of goodness.  If you haven’t already downloaded and installed it I highly recommend you do so.  Stay tuned for even more blog posts about it!

Hope this helps,

Scott

P.S. I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

66 Comments

  • Kudos to Microsoft on this technology. I'm highly impressed and anxiously await the opportunity to use this in a production application.

  • I really enjoy these well-illustrated blog tutorials. I find either reading them or going through them step-by-step to be the quickest way to learn new features/technologies. The red outlines in graphics help draw the eye to the key part to notice, and your accompanying concise explanations reinforce the key point to note.

  • Excellent walkthrough! I did some ASP.NET MVC2 yesterday with EF and this was exactly what I was looking for!

  • I'm lucky in the fact that I've started learning MVC now.
    When I used linq to SQL previously it just felt awkward. Entity Framework and code first are fantastic.
    I cursed MS for getting through so many versions of MVC in the early days but using MVC 3 and EF with Code First just feels right together. Exciting times.

  • Is it possible to specify the ef dbcontext as an interface and when scaffolding it would instead be a constructor parameter?

  • As usally fantastic... EF Code First is really nice... but kind of frustating to use without Data Migrations... Hopefully, it's close enough to be released soon...

  • Argh, that CategoryId on the Product class in the given example is still a show-stoppper for me.

    Can't we come up with some better way for the scaffolding framework to figure that out? Entity Framwork doesn't need it, why should I have to put extra properties on a POCO just to satisfy the tooling? I like the promise of scaffolding too much not to care about this...

  • In my database about 500 tables, my SaveContext will contain 500 properties. What will be the guidelines for working with a large data base. Not have been better to add the function as GetEntity?

  • Hi Scott,

    At the beginning of step 4, I'd recommend building the project so that the newly added classes are recognized by the "Add Controller" window. Otherwise, you get a "No model classes are available" message in the model class.
    Hope this helps

  • Thanks.
    At the moment i can't create new project on mvc and ef, but i see so much potential.
    And as avrashow said before me, your posts/illustrated guides are wonderful for quick learning.

  • This is a phenomenal improvement over EF in .Net 3.5, well done to the team.
    In your walk-through above, it might be worth mentioning that you need to build the project after creating the model classes and the StoreContext, otherwise the add controller dialog isn't aware of the available options.

  • Is there a way to scaffold the full Model instead of having to scaffold entity by entity?. For prototypes i might want to just build the EF model and scaffold it with just one command.

  • How can we use the new ADO.NET DbContext Generator? I would like to used it on the "Data Context class" in the template instead of the Entity Context class.

  • Scott,

    Is or will EF scaffolding feature ever be available for Winforms, WPF and Silverlight?

    Cheers.

  • Is the scaffolding update-able? That is to say, I just recently created a new project and used this technique to build my pages and DB. But since then, I've had to add a few properties to some of my objects. So far, when I add a new property, I have just gone in and modified the Create/Edit/Index pages by hand to add the new field. Can I re-run the scaffolding and have it regenerate? Or will I get errors or a bunch of duplicate files, etc? How is that meant to work?

  • Is there any way to force code-first framework to use a specific data type in SQL? In your example it makes UnitPrice a "decimal" by default, can it automatically make it a "money" data type or does that have to be changed manually after the table is created?

  • Why always showing a simple entities examples.
    Show example that at least one entity has One-to-Many and Many-to-Many for relations :)

  • EF 4.1 is final or Release Candidate or beta or ...?
    How can I download ?
    Thank you for the answer

  • with EF CF you can make db prototype very fast, and it's very good for beginners but when you need to do something more serious it will be better to use EF database first. There was some trouble with cascade delete etc in previous builds of EF CF(I don't know about final) so you can waste more time on investigating problem than you save on fast database creation.

    So Scott we are waiting for more complicated database scenarios with cascade deleting editing and updating, and various scenarios of relationships.
    Thank.

  • I see what you are doing, but I think you are creating something that is going to get people in trouble. For one, you are bringing back the whole object when you don't need to. Most views are a combination of multiple object's properties and should be projected instead of going and getting everything to just show 3 different properties. I think you are setting people up for failure. Sure this works great with a few records, but once you start dealing with thousands and thousands of records, not so good for performance. Second, you have put the data layer directly into the client layer. I am a fan of having View Models that all layers have access to, but not having the data layer directly in the client layer. I generally love what you do, but I am not a fan of this.

  • Hi Scott!

    What an awesome feature this is, realy love the way you explain.
    Keep it up man.God bless you.

  • Any reason the Sql Ce 4 tooling doesn't work in non-web projects? I can't seem to use EF/.edmx to model entities from a Sql Ce 4 DB for a class library or WPF project -- the DB connection windows only shows the Sql Ce 3.5 provider.

  • Scott:

    The VM trial for TFS/VS2010 is nearing expiration (6/1/2011). Will that download be refreshed soon?

  • @BrianB: The easiest way of forcing a column to be a specific type is to use the column data annotation, e.g.

    public class Product
    {
    public int Id { get; set; }
    [Column(TypeName="varchar")]
    [MaxLength(50)]
    public string Name { get; set; }
    ...

    Right now it's not possible to override default conventions. We plan on adding this in a future release.

    Thanks, Tim

  • If you could combine MVC scaffolding with some sort of template based on knockout.js then you could have a pretty darn responsive crud service!!!

  • Love this Code First I've watched Steve Sanderson’s video a couple of times now can't wait for his MVC 3 book to come out I have his MVC 1 book he's a definite asset to your team good job picking him up. Scott Hanselman’s videos are the most entertaining and Informative way to learn anything. I keep my hand in Web Forms and MVC, Code First is the icing on the cake for both technologies it just doesn't get any better than this. There a are rumors being bandied about you taking a bigger roll in Azure and the cloud if so I think you might be able to reduce some of the road blocks we face when trying to migrate to the cloud I find there is a lack of tutorials real world walkthroughs and so on maybe combine it as part of the ASP.NET web site so we have one hub to learn from and we can start moving in that direction I'd like to be developing on all three platforms just a thought in any case keep up the great work

    Thanks

  • I would really like that ASP.NET MVC had out of the box support of the PRG (Post, Redirect Get) pattern. This is a very useful usability improvement. There is stuff out there that can help you in implementing this pattern (http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx).
    It would be great if it was implemented inside MVC, so that Scaffolding could make use of this best practice.

  • Great post as ever!

  • @Daniel,

    >>>>>>>> Is it possible to specify the ef dbcontext as an interface and when scaffolding it would instead be a constructor parameter?

    Yes - Steve Sanderson's videos and blog tutorials show how to enable this. You'll want to install the MvcScaffolding package using NuGet. This will enable a Repository based template that will pass in an interface as constructor argument to the Controller class. You can then optionally take advantage of ASP.NET MVC 3's dependency injection support to wire-up the creation of the interface to whatever DI container you want.

    Hope this helps,

    Scott

  • @Preetham Reddy

    >>>>>>> As usally fantastic... EF Code First is really nice... but kind of frustating to use without Data Migrations... Hopefully, it's close enough to be released soon...

    We should have the first public preview of data migrations out next month (June). Not far away now...

    Hope this helps,

    Scott

  • @kaa,

    >>>>>>> Argh, that CategoryId on the Product class in the given example is still a show-stoppper for me. Can't we come up with some better way for the scaffolding framework to figure that out? Entity Framwork doesn't need it, why should I have to put extra properties on a POCO just to satisfy the tooling? I like the promise of scaffolding too much not to care about this...

    Unfortunately we needed to require this in the first scaffolding iteration because of time constraints - I expect it will be removed as a requirement in the future. I'd recommend checking out Steve Sanderson's MvcScaffolding templates - I think those don't require it.

    Hope this helps,

    Scott

  • @Igor,

    >>>>>>> In my database about 500 tables, my SaveContext will contain 500 properties. What will be the guidelines for working with a large data base. Not have been better to add the function as GetEntity?

    Typically you only expose those tables that you are directly working with on your DbContext. So unless you need all 500 tables I'd recommend trimming the properties to just be the ones you need.

    You can also have multiple DbContext classes - and so another option would be to distribute the tables across them, and organize them in a logical way.

    Hope this helps,

    Scott

  • @Thomas,

    >>>>>>> At the beginning of step 4, I'd recommend building the project so that the newly added classes are recognized by the "Add Controller" window. Otherwise, you get a "No model classes are available" message in the model class.

    Good catch - I just updated the post with those instructions

    Hope this helps,

    Scott

  • @Richard,

    >>>>>>>> In your walk-through above, it might be worth mentioning that you need to build the project after creating the model classes and the StoreContext, otherwise the add controller dialog isn't aware of the available options.

    Good catch - I just updated the post to call this out.

    Thanks,

    Scott

  • @Javier,

    >>>>>>>> Is there a way to scaffold the full Model instead of having to scaffold entity by entity?. For prototypes i might want to just build the EF model and scaffold it with just one command.

    The built-in tools scaffolding doesn't support this - but I think you can do this with the MvcScaffolding package that Steve Sanderson maintains. Check out his blog posts above to learn more on how you might be able to enable this.

    Thanks,

    Scott

  • @Stefan,

    >>>>>>>> How can we use the new ADO.NET DbContext Generator? I would like to used it on the "Data Context class" in the template instead of the Entity Context class.

    Are you talking about the EF Designer? If so, I think installing the EF 4.1 install (not via MVC but from the ADO.NET site) will allow you to change the code generator to use the DbContext one.

    Hope this helps,

    Scott

  • @folorunso

    >>>>>>>> As detailed and clear as ever! This is really kool !! Scott is the news(or rumor) of ur imminent transfer to the AZURE TEAM real ? I just hope Redmond is making a right calculation here.I will suggest you head both Azure and Dev Div teams together. Missing the kind of mentoring u'v shown the community will be a disaster to say the least...

    I'm now involved in Azure - but am also very involved with .NET and VS too. I still run a lot of the .NET and some VS teams (including ASP.NET, WCF, WF, AppFabric, VS Web Tools, IIS, WebMatrix and more).

    So don't worry - I'm not going anywhere... ;-)

    Thanks,

    Scott

  • @Luciano Evaristo Guerche (Gorše)

    >>>>>>> Is or will EF scaffolding feature ever be available for Winforms, WPF and Silverlight?

    I believe we are looking at a few options like this. Check out RIA Services for one approach that you can use that dramatically improves productivity when working with data.

    Hope this helps,

    Scott

  • @Todd Davis

    >>>>>>>>> Is the scaffolding update-able? That is to say, I just recently created a new project and used this technique to build my pages and DB. But since then, I've had to add a few properties to some of my objects. So far, when I add a new property, I have just gone in and modified the Create/Edit/Index pages by hand to add the new field. Can I re-run the scaffolding and have it regenerate? Or will I get errors or a bunch of duplicate files, etc? How is that meant to work?

    Yes - you can just re-run the scaffolding. VS will then prompt you as to whether you want to overwrite the Controller class or just the view templates. You can select only what you want to update.

    Hope this helps,

    Scott

  • @RyanB,

    >>>>>> Is there any way to force code-first framework to use a specific data type in SQL? In your example it makes UnitPrice a "decimal" by default, can it automatically make it a "money" data type or does that have to be changed manually after the table is created?

    Yes - check out timlav's comment above. It shows how you can customize it.

    Hope this helps,

    Scott

  • @Me,

    >>>>>>> Why always showing a simple entities examples. Show example that at least one entity has One-to-Many and Many-to-Many for relations :)

    I'll show some more advanced scenarios in future posts. I thought a simple scenario to start would be good :) BTW - the sample above does have a 1:M relation.

    Hope this helps,

    Scott

  • @ignatandrei

    >>>>>>> EF 4.1 is final or Release Candidate or beta or ...?

    EF 4.1 is now final. It is automatically included with ASP.NET MVC 3. There is also a release link in my post above: http://blogs.msdn.com/b/adonet/archive/2011/04/11/ef-4-1-released.aspx

    Hope this helps,

    Scott

  • @Batslhor,

    >>>>>>> So Scott we are waiting for more complicated database scenarios with cascade deleting editing and updating, and various scenarios of relationships.

    I need to check - but I thought cascade delete is now supported.

    Hope this helps,

    Scott

  • @mikem,

    >>>>>>>> I see what you are doing, but I think you are creating something that is going to get people in trouble. For one, you are bringing back the whole object when you don't need to. Most views are a combination of multiple object's properties and should be projected instead of going and getting everything to just show 3 different properties. I think you are setting people up for failure. Sure this works great with a few records, but once you start dealing with thousands and thousands of records, not so good for performance. Second, you have put the data layer directly into the client layer. I am a fan of having View Models that all layers have access to, but not having the data layer directly in the client layer. I generally love what you do, but I am not a fan of this.

    Scaffolding isn't for everyone - and for some scenarios might not be appropriate. Having said that, the scaffolding system itself is very extensible (check out Steve Sanderson's posts and video above). If you want to use a repository pattern or encapsulate into ViewModels you can still do that.

    Hope this helps,

    Scott

  • @Ron,

    >>>>>>> Any reason the Sql Ce 4 tooling doesn't work in non-web projects? I can't seem to use EF/.edmx to model entities from a Sql Ce 4 DB for a class library or WPF project -- the DB connection windows only shows the Sql Ce 3.5 provider.

    Unfortunately it is a bit goofy. You can use SQL CE 3.5 in non-web projects, and SQL CE 4 in web projects - but not vice-versa. Sorry for the confusion - I agree it is kind of weird.

    Thanks,

    Scott

  • @Joel,

    >>>>>>> The VM trial for TFS/VS2010 is nearing expiration (6/1/2011). Will that download be refreshed soon?

    I checked with our marketing team and they said it will be updated soon. Here is more details about how the VM is maintained: http://blogs.msdn.com/b/briankel/archive/2010/06/25/now-available-visual-studio-2010-rtm-virtual-machine-with-sample-data-and-hands-on-labs.aspx

    Hope this helps,

    Scott

  • Scott,

    How do you align the { get; set; } accessors for your properties? I'm sure there's an easier way than hitting the space bar!

  • I find it interesting that the scaffold creates the "delete" navigation path as a link.

    This seems kin of dangerous as it means anyone using one of those "speed up the internet" plugins that preloads all the links on a page will have a lot of fun... ;-)

  • Friday, May 06, 2011 9:46 PM by ScottGu

    >>>>>>>@Me,

    >>>>>>>>>>>>>> Why always showing a simple entities examples. Show example that at least one entity has One-to-Many and Many-to-Many for relations :)

    >>>>>>>I'll show some more advanced scenarios in future posts. I thought a simple scenario to start would be good :) BTW - the sample above does have a 1:M relation.

    >>>>>>>Hope this helps,

    >>>>>>>Scott

    1:M is not enough for real world as it is easy :)
    M:M is a bit of a challenge, especially to visualize it. So it will be nice to see how MVC, Scaffolding and/or MvcScaffold can help in that almost everyday task :)

    Regards

  • Scott,

    The ability of data scaffold together with Steve Sanderson's explaination of extending the scaffolding framework to use custom templates, make this a truly RAD tooling. Amazing productivity that can be acheived without sacrificing the best practices that one has come to implement over years of experience.

    Thanks
    Deepak

  • Very nifty, I've used linq-to-sql for my past few projects but seeing the simplicity of EF in examples like this will force me into at least test driving it for my next project.

  • @Jim,

    >>>>> How do you align the { get; set; } accessors for your properties? I'm sure there's an easier way than hitting the space bar!

    I actually use the spacebar :)

    I don't use that format for when I code myself - but find it useful to make the code more readable for blog posts.

    Hope this helps,

    Scott

  • @Tom,

    >>>>>>> Hi Scott. I was wanting to use SqlTableProfileProvider, but after reading connect.microsoft.com/.../add-support-for-the-sql-table-profile-provider-in-asp-net-4-web-applications it appears that Microsoft wants us to use the Entity Framework to implement this. Do you know of any samples around the internet that might show how to implement a Profile Provider using EF Code-First?

    I believe we are going to release new providers shortly that are built with EF Code First. I sent an email to someone on the team about this but haven't heard back on the specifics of the plan. If I hear more I'll post a follow-up comment.

    Hope this helps,

    Scott

  • @Doug,

    >>>>>>> I find it interesting that the scaffold creates the "delete" navigation path as a link. This seems kin of dangerous as it means anyone using one of those "speed up the internet" plugins that preloads all the links on a page will have a lot of fun... ;-)

    The listing page is a link that goes to a /Delete action. That return an HTML confirmation page, though, that requires a form post to do the actual delete. So search engines and others won't inadvertently cause deletes.

    Hope this helps,

    Scott

  • @Me,

    >>>>>>> M:M is a bit of a challenge, especially to visualize it. So it will be nice to see how MVC, Scaffolding and/or MvcScaffold can help in that almost everyday task :)

    Watch Steve Sanderson's video on MvcScaffolding above - he shows off M:M scenarios with scaffolding and EF code first.

    Hope this helps,

    Scott

  • >>>>>>> M:M is a bit of a challenge, especially to visualize it. So it will be nice to see how MVC, Scaffolding and/or MvcScaffold can help in that almost everyday task :)

    Watch Steve Sanderson's video on MvcScaffolding above - he shows off M:M scenarios with scaffolding and EF code first.

    Hope this helps,

    Scott

    That's interesting but what about example of something like
    Person M:M Address where you can pick more than one address for a person and also to assign more than one Person to an address. Wonder where that can be used? Well in cases when person has more than one property and also you have list of address that you want assign owners to. So you do not ask user to fill People table then Address table and then go to third page to establish the relation. Best will be if user add new person record or pick it from list (if already exists) then either create on fly addresses either search addresses and add multiple of them to the person. Same at the address page.

    Best Regards

  • Hi Scott

    Trying out the example and noticed that if you add a [Display(Name="Stock Level")] attribute to the Product.UnitsInStock property this title comes through in the Edit page but not on the Index page.

    It's a little thing I know but would be great if it worked (or if I'm just missing something). Otherwise works great, loving all the progress in this area.

    Cheers
    Nathan

  • Scott,

    Thanks again for the great work. I just want to second a request for a many-to-many with dynamic javascript manipulation of the object tree on the client. A sample like this contact editor: http://knockoutjs.com/examples/contactsEditor.html though not necessarily using knockout on the client, but with the addition of a many-to-many (e.g. associating the contact with a group). I've been trying to get this to work with Code First and MVC. It does work with a lot of manipulation, so I'm wondering if there's a straightforward way of doing it. After all, I'm sure it's a fairly common scenario to build the object tree on the client these days.

    Thanks!

  • Is this scaffolding based on mvcscaffolding? If so how do we extend it as CustomScaffolder appears to have been removed and I can't find any documentation on extension.

    Thanks!

  • > I believe we are going to release new providers shortly that are built with EF Code First. I sent an email to someone on the team about this but haven't heard back on the specifics of the plan. If I hear more I'll post a follow-up comment.

    >Hope this helps,

    > Scott


    Thanks Scott. Can't wait until they appear!

  • Hey, Scott,Now I'm upgrading from "database first" to "code first" by your guide "Using EF Code First with an Existing Database". But the generated pocos is so pure that it has lost column's information like length, nullable, description and so on. Can I have a way to make a perfect upgrating? Thank you.

  • Hey Scott

    Thats really a nice article, I am going to explore it more. One thing that I would like to ask here is I see a "Logon" link here, so can you tell me (or suggest some article on web) that how EF code-first and data scaffolding can help auto generate the login functionality too (I mean UI code and data controller)?

    cheers

    Mutahar

  • I am using Visual Studio 2010 Premium, and recently upgraded to Visual Studio 2010 SP1, Entity Framework 4.1, and ASP.NET MVC 3 Tools Update.
    All of these upgrades used the released version of the product; no betas were involved.
    I performed the tutorial above (EF Code First and Data Scaffolding with the ASP.NET MVC 3 Tools Update) and it worked perfectly.
    However the ADO.NET Entity Framework Template is no longer visible.
    I have searched quite widely on the web for a solution, but to date all that I have found is that a number of other people are experiencing the same problem and do not have a solution.
    Any help will be appreciated. Thanks.

  • @phicorp,

    Can you send me email (scottgu@microsoft.com) with details about this issue? I'd then be happy to have someone help.

    Thanks,

    Scot

  • @Scott
    Thank you very much for your offer of help.
    I will email you shortly.

  • Scott,

    ASP NET MVC 3 Tools you should be, I really appreciate the information you provide very useful updates.
    What should I do if I found out that the information you gave your thank you.

Comments have been disabled for this content.