Wednesday, March 19, 2008

Entity Framework - making life easier for my coders

Set up wise it can be a bit frustrating... mainly because there are three xml files (well one big one with three sections.) One handles the SQL Server table layout, the second handles what your objects will look like, and the third maps between the to...

Now the neat bit...
To access your data you just need this...

NorthwindDbContext nwContext = new NorwindDbContext;

the class above is the autogenerated Entity Framework class (e.g. the huge edmx file it makes when you point it at you database...)

Want to get a client?

Client myClient = nwContext.Client.Where("it.ClientID = @id", new ObjectParameter("id", TheValueOfTheClientIDGoesHere)).First();

So... create a client object (based on what EF mapped...) then get said object from the "context" the rest is parameter passing... the .First() is simply to grab the top record. (it populates the object for you... yay.)

change the values of the properties of you client e.g. myClient.Name = "something new" and then persist it back... how? Well if you let EF do all the work then type:

nwContext.SaveChanges();

that's it... oh you're dba created fancy custom sprocs that return error codes? First you get to go back to the xml files, but at least they provide a nice interface now... right click on the entity (Client) in the big map and choose mapping details. You can then override the default Save/Update/Delete by mapping to the appropriate sprocs. Downside you have to map all three. Also you have to account for Foreign Keys even if you only do soft deletes. Minor annoyance, but hey after that all you coders have to type is:

try
{nwContext.SaveChanges(); //cause hey we re-mapped it to the sproc}
Catch (Exception ex)
{
//don't forget the db's error code is in the InnerException
ex.InnerException //do something with me...
}

That's it...
Adds and deletes are similar... more on those later.

So overall I'm warming to Entitiy Framework for ADO .Net. It's providing the right level of abstraction. Once the mappings are done the developer has less to worry about and can get down to coding and testing.

Now once MVC gets more polish the two together should be quite nice. Database abstraction and no more ViewState!

0 Comments:

Post a Comment

<< Home