Accessing your own data with MVC Forum's data provider.

So you're building a site, and you want to use MVC Forum as part of the solution. To make things easier you could go ahead and use the Entity Framework data provider to access your own data, if you want to put it in the same database as the MVC Forum data.

That has the added bonus of making it possible to reference MVC Forum objects, so if you need to have an author/owner referenced on your own objects, it's easy-peasy!

Time for a short example:

	public class NewsItem {
		public Int32 Id { get; set; }
		[Required]
		public virtual ForumUser Author { get; set; }
		[Required]
		public virtual ForumUser LastEditor { get; set; }
		[Required]
		public DateTime Created { get; set; }
		[Required]
		public DateTime LastChanged { get; set; }
		[Required]
		[StringLength(100)]
		public String Headline { get; set; }
		[Required]
		[StringLength(400)]
		public String Digest { get; set; }
		public String Body { get; set; }
	}

Nothing tricky here! So how do you plug your own objects into Entity Framework and MVC Forum's database context? Well, you create 2 extra classes in your class library, a database context class, and a data provider configuration class. Both of these classes should inherit from the same 2 classes in MVC Forum's Entity Framework data provider. Here you go:

	public class ModellingContext : MVCForumContext {
		public ModellingContext(String connectString)
			: base(connectString) {
		}
		public DbSet<NewsItem> NewsItems { get; set; }
	}

If you've ever worked with Entity Framework, you should recognize everything above, it's just a class inheriting from DbContext, so you can do whatever you would normally do here with a regular DbContext class.

	public class DataProviderConfiguration : mvcForum.DataProvider.EntityFramework.DataProviderConfiguration {
		public override void Configure(IDIContainer container) {
			base.Configure(container);
			container.UnRegister<DbContext>();
			container.RegisterPerRequest<DbContext, ModellingContext>(new Dictionary<String, Object> { { "connectString", ConfigurationManager.ConnectionStrings["mvcForum.DataProvider.MainDB"].ConnectionString } });
		}
	}

First off we unregister DbContext, this is to remove the context registered in the base class, we want to make sure our own context class is fetched whenever the DbContext object is needed. Well, that was easy! Just remember to use your own, new data provider configuration class in the global.asax.cs file, it's needed in the ApplicationConfiguration constructor.

Categories: MVC Forum - EF41 - Alpha 2

Posted by Steen F. Tøttrup on 02 October 2011 21:28. There are 0 comments.

Write new comment