views:

94

answers:

1

I'm using the Entity Framework as my ORM for an ASP.Net (webforms) application. Suppose I had a "list/detail" set of pages in my application, when you click on a row in the list page I would want to pass an ID of some type for that row to a detail page, which I'd then use to load the row from my data layer. In my specific case, the primary key is simply a "rowId" identity column.

EF, however, seems to prefer to "hide" the primary/foreign keys so that you don't get access to them (by default).

I'm new to EF, and I'm wondering if there is a best-practice for uniquely identifying a row outside of the context of the entity. I imagine I could add a uniqueidentifier column to my record and a matching property to my entity model, but it seems redundant to effectively have 2 unique identifiers for the row. Is there a better way to carry around an identifier out at the presentation layer?

In my _ItemDataBound() event handler, I'm thinking I can do something like:

var announcement = (Announcement) e.Item.DataItem;
string rowID = announcement.EntityKey.EntityKeyValues[0].Value.ToString();

Is this recommended, or just working against the framework?

Thanks in advance.

Scott

+1  A: 

No, what you're doing does not "work against the (Entity) Framework." This is not to say that it couldn't be improved, however:

  1. I know this is not MVC, but even in WebForms I still think it's a good idea to have some separation between your data layer and your web pages. I would probably use the Repository pattern with a presentation model here rather than give the page direct knowledge of the Entity Framework.
  2. Since you have already cast the Announcement into its proper type, you can access the ID value directly, rather than going through the EntityKey. Then, at least, your page only has knowledge of Announcement instead of the Entity Framework.
  3. The current code presumes that there is an EntityKey (not always true, especially with newly-inserted entities which have not yet been committed to the database) and that it has only one column. It's a good idea to test those presumptions and throw a meaningful exception instead of letting them blow up with a null reference if they are violated.
Craig Stuntz
Implementing the repository pattern was actually going to be my next refactoring :) I'm not sure where I got the impression that the .RowID property wasn't going to be available to me... that works fine for me in this case. Good point on #3... I'm new to EF and feeling out what I should and should not be doing with it.
Scott Mayfield