|
I reailze that the Entity Framework is designed very specifically to serve as a queryable model that fronts a back-end database. The issue I have with that is that the back-end database is not always immediately accessible to my web application. In fact, sometimes, the back-end database is completely inaccessible depending on the particular web application.
One way around this is people have often created facades or services that front a specific subset of SQL data and expose them over a channel through which the web site can communicate, essentially a poking a straw through the otherwise airtight firewall. This is a decent idea and makes a lot of architectural sense, but usually involves a lot of busywork involved in setting up the service or even a proxy service if necessary, figuring out serialization and usually it ends up creating a lot of redundant effort for developers for very little gain in return.
Instead, what we can do is create an ADO.NET Data Service (formerly codenamed Astoria) that exposes the entity data model over a RESTful URL syntax using the ATOM/APP protocol as a serialization format.
I've covered it before and there are lots of blog entries on doing it, but I created an Astoria client class file for my demo using the WebDataGen.exe tool that comes with the entity framework. Once I have that class, I can just add that class to my MVC project (I put it in the App_Code folder to let me access the data types from anywhere in the project).
Then, to access data in the controller, I can easily do things like this:
[ControllerAction]
public void Index()
{
var accountList = from account in entityClient.Accounts
orderby account.Name
select account;
RenderView("Index", accountList.ToList());
}
The view is a strongly typed MVC view that works with data of type List<Account>. Now, how do you deal with reference-loading? For example, what if you want to use some Ajax to dynamically display some child rows when you hover over the parent row? To do that, you can just run a foreach on the accounts as follows:
accountList.ForEach( acct => entityClient.LoadProperty(acct, "Transactions"); );
Because the information coming from the ADO.NET Data Service (Astoria) might not always conform nicely to what you're rendering in your view, you can also create a language extension that extends the Astoria data type and converts it to a model view type:
accountList.ForEach ( acct =>
{
entityClient.LoadProperty(acct, "Transactions");
acctFacade.Accounts.Add( acct.ToViewModel() );
}
);
As I start getting more and more toward a functioning application, I will begin posting more articles on MVC development in ASP.NET.