简体   繁体   中英

How do I create a read only entity in the entity framework?

I am loading a graph of related entities from the database using ADO.NET MVC and the Entity Framework. One of the entities needs to be modified in memory, but not have changes persisted back to the database when other entities in the graph are changed.

At this time I have attempted to use the MergeOption.NoTracking and the MergeOption.OverwriteChanges but they both seem to be ignored and any changes in the entity set that should not be modified being persisted to the store.

A snippet of the code that I use to load the entity graph from the database is given below:

QuizDBEntities entities = new QuizDBEntities();
ObjectParameter[] searchParameters = { new ObjectParameter("contestantID", contestantID) };
entities.QuestionSet.MergeOption = MergeOption.NoTracking;

var query = entities.ContestantSet
  .Include("Quiz.Questions.Categories.Options.Answer")
  .Include("Answers")
  .Include("Quiz.Questions.Filters.FilterAnswers")
  .Where("it.ContestantID == @constestantID", searchParameters);

Contestant contestant = query.First();

I have also attempted to set the MergeOption after the query is constructed but before being executed.

Any help would be greatly appreciated.

The nature of the problem you have is in the way EF deals with relationships. In EF, relationships are first class members, just like entities. That is why object graph,that you are retrieving, is actually collection of entities and relationships. All entities and relationships inside of object context are either connected to the object context either disconnected. That's the Entity Frameworks "Platinum rule" :

When I first noticed that an entity had been attached to the ObjectContext even though I hadn't explicitly called for this in my code, I was a little taken aback because I had trusted the Entity Framework not to break what I thought of as "the golden rule": that is, it would not do anything I hadn't specifically told it to do. Once I understood why the entities were being automatically attached to the context when I was attaching them to a graph—and why that was necessary—I determined that this must be the Entity Framework's platinum rule, because it overruled the golden rule.

Juile Lerman, Programming Entity Framework

"Golden rule" says that EF will never do something you didn't explicitly tell it to do.

So, the "read-only" entity is detached entity. You can achieve it the way you already did. or if you call Detach method on ObjectContext. Entities in object graph can be either attached either detached from the ObjectContext.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM