This project is read-only.

Adding you own data

You'll probably need to store some custom data in you MVC application, so how do you add business objects to the database and use the data provider to access them?

The examples below are done with the entity framework provider, so this will probably have to be done in a different way with other providers.

First create your business classes:

using System.ComponentModel.DataAnnotations;
using MVCBootstrap;

public class FavoriteColor {
	public Int32 Id { get;set; }
	public String Color { get;set; }
	public virtual User User { get;set; }

And then it's time to let entity framework know that we want this object represented in the database.

using System.Data.Entity;

public class MyCustomContext : MembershipDbContext {
	public MyCustomContext(String connectString) : base(connectString) { }

	public DbSet<FavoriteColor> FavoriteColors { get; set; }
public class DataProviderBuilder : MVCBootstrap.EntityFramework.DependencyInjection.DataProviderBuilder {
	public override void Configure(IDependencyContainer container) {
		Database.SetInitializer<MyCustomContext>(new CreateDatabaseIfNotExists<MyCustomContext>());
		container.RegisterPerRequest<DbContext, MyCustomContext>(new Dictionary<String, Object> { { "connectString", ConfigurationManager.ConnectionStrings["DataProvider.MainDB"].ConnectionString } });

Remember to replace the DataProviderBuilder class with your new DataProviderBuilder class in the Application-Start method in global.asax.cs, to let the dependency injection framework know about your changes. That's about it! So let's create a controller that will list all favorite colors:

public class FavoriteColorController : Controller {
	public FavoriteColorController(IRepository<FavoriteColor> favRepo) { /* ... */ }
	public ActionResult List() {
		IEnumerable<FavoriteColor> all = favRepo.ReadAll();
		// TODO: Whatever


Querying data without killing performance


Last edited Jan 2, 2013 at 6:59 AM by steentottrup, version 11


No comments yet.