I've been thinking for a while about a series of blog posts I'd like to write explaining various Entity Framework concepts, particularly those related directly to writing code using the framework--by that I mean that I will concentrate more on using the API to write object-oriented programs which do data access and less on some other kinds of topics like writing and debugging the XML mapping, using the designer, etc. Some of this will be pretty basic, but many of them are the kinds of things that come up fairly often in our own internal discussions as well as on the forums and such. Hopefully this will be valuable, please let me know what you think, if there are topics you would especially like me to cover, or if there's anything I can do to make it more useful.
I'm going to use a common model/database for my samples which I call DPMud. It's something that a few friends and I created and maintain as a fun side-project which is an old-style multi-user text adventure (MUD) built using the entity framework. The architecture is not something that will scale well (every real-time event in the system persists to the database, and users learn about events by querying the database), but it works reasonably well for a few users at a time, it's an environment which is very convenient for us to develop in, and it has turned out to be a decent example for exercising all sorts of entity framework functionality. It even does a reasonable job of stressing the system.
In order to help you get a feel for the model, here's an abbreviated version of the diagram:
Essentially I have a many-to-many self relationship for rooms, but because I need a "payload" on that relationship (some properties on the relationship itself rather than the rooms), I chose to create another entity type called Exit and then have two 1-many relationships between Rooms and Exits--one of those relationships represents all of the exits out of a room, and the other relationship represents all of the entrances to the room. The other parts of the model are actors which are related to rooms, and items which can be related either to a room or an actor. The model doesn't have a good way to enforce that an item must be related either to a room or an actor but not both or neither, but I've added check constraints to the DB which handle that enforcement. In the real game there are also events which relate to each of the other entity types as well as a large inheritance hierarchy of actor types and event types among other things, but those make the model diagram very hard to read, so I've left them out.
This diagram corresponds to my CSDL file which is the XML file describing my conceptual model. If you'd like to look that over, you can find it here. Well, that CSDL file actually has a few things not present in the diagram, but it is simplified considerably from the full model used in our game. For completeness, you can also have a look at the SSDL and the MSL. I know I'm a bit "old school" when it comes to these things since I've been working on the EF since well before we had a designer (funny to say that about a not-yet-released project), but I've authored each of these files by hand rather than using the designer. I'll also point out, in case some of you are unaware, that the designer uses a file called EDMX to store all of the metadata about an EF model--this one file includes the CSDL, MSL and SSDL just in separate sections within it. When it comes to runtime, the system requires the three separate files, and the designer projects automatically create them in your application out directory. So, I will talk about the three files separately and even play some tricks that don't work with the designer today rather than describing the default designer experience.
The one other thing I'll say about DPMud is that it was built from the beginning as rich windows client which talks direclty to the database. So most of our initial apps will work that way. This is nice, because these are some of the easiest apps to write, but as we go through the series we probably will also spend some time exploring other app architectures like web services and web apps.
OK. So enough about my funny little sample. Let's cover some EF concepts, shall we? There are three things I'd like to talk about in this post which are all related to getting any basic app up and running (once you are done creating the metadata for the model, generating the basic entity classes, etc.):
If you are going to build up these parts dynamically, then naturally the recommended way to do so is using a connection string builder, and EntityConnectionBuilder makes this easy. For the provider connection string, you can of course do a similar thing using something like SqlConnectionBuilder. So, the whole thing together would look like this:
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.MultipleActiveResultSets = true;
sqlBuilder.DataSource = ".";
sqlBuilder.InitialCatalog = "dpmr";
sqlBuilder.IntegratedSecurity = true;
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
entityBuilder.Metadata = "res://*/";
entityBuilder.Provider = "System.Data.SqlClient";
using System;
using System.Data.EntityClient;
using System.Data.SqlClient;
using DPMud;
namespace DPMud
{
public partial class DPMudDB
[ThreadStatic]
static DPMudDB _db;
static string _connectionString;
public static string ConnectionString
get
if (_connectionString == null)
// insert code from above which uses connection string builders here //
_connectionString = entityBuilder.ToString();
}
return _connectionString;
public static DPMudDB db
if ((_db == null) && (ConnectionString != null))
_db = new DPMudDB(ConnectionString);
return _db;
So what do we get from all this? Well, once we have this foundation laid, writing a program which accesses the database using our strongly typed context becomes pretty darn simple (even if we have multiple threads), and that program can itself just be a single EXE with the entire model and all of its metadata in that one assembly (this is what we do for DPMud—nothing quite like drag-and-drop deployment).
Here’s the code for a simple program which prints out a list of all the rooms and items in the DPMud database but does so from two threads running concurrently. Note: you can set break points in each of the loops and step through the program seeing things interleave nicely, but if you actually run the program there’s a good chance all of the rooms will print together and the items the same because the total time required is relatively small so there may not be that much time-slicing between the threads.
using System.Threading;
namespace sample1
class Program
static void Main(string[] args)
Thread thread = new Thread(new ThreadStart(Program.PrintItems));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
foreach (Room room in DPMudDB.db.Rooms)
Console.WriteLine("Room {0}", room.Name);
static void PrintItems()
foreach (Item item in DPMudDB.db.Items)
Console.WriteLine("Item {0}", item.Name);
Fun huh? OK. Yes I admit it, I’m a total geek, but I think it’s pretty fun.
Until next time,Danny