Sunday, December 16, 2012

Read Only Entities in the Entity Framework

Recently I had a need in a project to have a few read-only entities because the tables didn't belong to my application. I didn't want to create views into those tables, I just wanted a read-only entity. If we set the entity's state such that it isn't tracked in the ObjectContext, then no changes would ever be persisted for it.

The following allows usage of context.States (ie states of the USA) but doesn't track any changes.

/// Using a dbquery since this is readonly.
/// </summary>
public DbQuery<State> States
{
  get
  {
    // Don't track changes to query results
    return Set<State>().AsNoTracking();
 }
}

6 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. If you are interested in earning money from your traffic via popup ads, you should try one of the most reputable networks - PopAds.

    ReplyDelete
  5. Hi there! Nice stuff, do keep me posted when you post again something like this! Tamilnadu Ration Card Application

    ReplyDelete
  6. Best work you have done, this online website is really cool with great facts. jiofi settings

    ReplyDelete