Entity Framework in detached mode with MVC application - asp.net-mvc-3

I have started working out with Entity Framework (EF) for an MVC n-tier application. It would seem that very obvious that this being a web application (which is stateless), I would have to use detached object models. There is no ambiguity with doing an Add operation. However when doing an edit there are here are two ways
Fetch the original object in context, attach the updated object and
then save to database. Something like mentioned in answer to this
question
EF4 Context.ApplyCurrentValues does not update current values
Set individual modified properties explicitly using the IsModified property of individual fields of the object like
mentioned in this article
http://msdn.microsoft.com/en-us/data/jj592677.aspx
Method 1 has disadvantage of having to load object into memory from database each time an update needs to be performed.
Method 2 would require having to manually pass which fields to be set as IsModified to true from wherever the object an be updated. So for e.g. for each object, I may need to create a boolean collection object for each field of the object.
e.g.
SaveEntity(EntityClass e, EntityStateClass ec)
{
context.Entry(e).Property("Name").IsModified = ec.NameState;
context.SaveChanges();
}
class EntityStateClass{ public bool NameState;}
I would prefer method 2 simply for the sake of performance but I am hindered by the n-tier architecture and repository pattern I am using. My Repository interface restricts save method for any object to be
SaveEntity(EntityClass e);
So I cannot pass the "state" object. Context class is not available and should not be available outside DAL. So I cannot set property outside. Is there any "proper" way to achieve this ?
Note: Self-Tracking Entity is also out of question since I cannot send entities with state to client (the browser) since I am intent on keeping the html lightweight.
EDIT: After a lot of thinking, I am trying to use following mechanism to keep track of modified state for each field in my domain class
Declare a partial class for entity class.
For each field that is updateable, declare a boolean property like "IsModified_FieldName"
Set the "IsModified_FieldName" property when the field is set.
However for this I need Entity Framework to generate explicit properties for me instead of implicit properties that it auto-generates. Does EF provide an handle to do this ?
Here is sample code of what I am trying to achieve
//Save Method for class EntityClass.
SaveEntity(EntityClass e)
{
context.Entry(e).Property("Name").IsModified = e.IsModified_Name;
context.SaveChanges();
}
//EntityClass is class autogenerated by EF
public partial class EntityClass
{
//This is auto-generated property by EF
public string Name {get; set;}
/* This is what I would like EF to do
private string name;
public string Name
{
get {return Name;}
set {
name = value;
//this is what I would like to do
this.IsModified_Name = true;
};
}
*/
}
//This is another partial definition for EntityClass that I will provide
public partial class EntityClass
{
//This property will be set to true if "Name" is set
public bool IsModified_Name {get; set;}
}
PS: It seems the information I have provided is not sufficient and therefore there are no responses.
I am using DbContext (Database first model)
EF auto-generates the class files for me. So each time I update my database, the class files are regenerated.

To your concrete question: The entities are generated by a T4 template and it should be possible to modify this template (which is in text format) to generate the entities in a way you want to shape them.
But I have a few remarks about your concept:
In a web application data are usually changed by a user in a browser. To have a definite knowledge what really has been changed you need to track the changes in the browser (probably by some Javascript that sets flags in the data (a ViewModel for example) when a user edits a text box for instance).
If you don't track the changes in the browser what happens? The data get posted back to the server and you don't know at the server side (with MVC in a controller) which property has been changed. So, your only chance is to map all properties that has been posted back to your EntityClass and every property will be marked as Modified, no matter if the user really did a change or not. When you later call SaveChanges EF will write an UPDATE statement that involves all those properties and you have an unnecessary overhead that you you want to avoid.
So, what did you win by setting individual properties instead of setting the whole entity's state to Modified? In both cases you have marked all properties as Modified. Exceptions are partial changes of an entity, for example: You have a Customer entity that has a Name and City property and a view that only allows to edit the Name but not the City and a corresponding ViewModel that only contains a Name property. In this case your procedure would only mark the Name property of the Customer entity as Modified but not the City. You might save here a little bit because you don't save the City property value to the database. But you still save the Name even if it didn't change.
If you use solution 1 (ApplyCurrentValues) you have to load the entity first from the database, yes, but it would only mark the properties as Modified that really changed compared to their values in the database. If the user didn't change anything no UPDATE would be written at all.
Keep in mind that you are only at the beginning to implement your concept. There are other changes to the data that can happen in the browser than only scalar property changes, namely relationship changes. For example a user changes the relationship from an Order to a Customer or you have a view that has an Order and a collection of OrderItems and the user cannot only edit the Order header but also edit the OrderItems and remove and add new OrderItems. How do you want to recognize when the data come back from the browser to the server which collection item has been added and which has been removed - unless you track all those changes in the browser and send tracking information back to the server in addition to the actual data or unless you reload the Order and OrderItems from the database and merge the changes into the original entities from the database?
Personally I would vote for option 1 for these reasons:
You can use real POCOs that don't carry additional tracking information. (BTW: I have some doubt if you aren't reinventing the wheel by implementing your own tracking that EF change tracking proxies provide out of the box.)
You don't need to track changes in the browser which can become quite complex and will require Javascript in every Edit view to write change flags into hidden form fields or something.
You can use standard features of EF without having to implement your own tracking.
You are required to load entities from the database when you want to update an entity, that's true. But is this the real performance bottleneck in a web application where data have to run through the wire back and forth (and reflection (which isn't really known as to be fast) is involved by the model binder)? I have nothing said if your database is remote from the web server and connected by a 9600 baud modem. But otherwise, your plan is not only premature optimization, it is kind of premature architecture. You are starting to build a potentially complex architecture based on "it could be slow" to solve a performance problem that you actually don't know of whether it really exists.

Related

'Existing Entity' constraint

I'm reading some data from an excel file, and hydrating it into an object of class A. Now I have to make sure that one of the fields of the data corresponds to the Id of a specific Entity. i.e:
class A{
protected $entityId;
}
I have to make sure that $entityId is an existing id of a specific entity (let's call it Foo). Now this can be achieved using the choice constraint, by supplying the choices option as all of the existing ids of Foo. However this will obviously cause a performance overhead. Is there a standard/better way to do this?
I'm a bit confused about what you are doing, since you seem to talk about Excel parsing, but at the same time you mention choices, which in my opinion relate to Forms.
IMO you should handle directly the relationship to your entity, instead of only its id. Most of the time it is always better to have directly the related entity as attribute of your class A than only the id, and Symfony manipulates such behaviours pretty well.
Then just have your Excel parser do something like this:
$relatedEntity = $this->relatedEntityRepository->find($entityId);
if (!$relatedEntity) {
throw new \Exception();
}
$entity->setRelatedEntity($relatedEntity);
After doing this, since you were talking about Forms, you can then use an EntityType field which will automatically perform the request in database. Use query_builder if you need to filter the results.

Selective disabling of lazy loading with Database First method

I am not interested in disabling lazy loading for the entire context. I want only to selectively disable lazy loading for a few key navigational properties.
With the Code First method, I understand how to selectively disable lazy loading:
public virtual Person Requestor { get; set; } //lazy loading enabled
...
public Person Requestor { get; set; } //lazy loading disabled
However with the Database First method, this is code generated from a template so this modification is going to be lost on the next regeneration.
Is there a way to modify the model or template generator for such selective disabling of lazy loading?
I don't know of a way. But if you are going to use the Entity code generator you could build in a warning system so that when the code is re-generated you get notified immediately (depending on your build strategy).
So what I would do is for the selected entites, say the entity is Request and the property in question is Requestor then write a test to assert that the property is NOT virtual
[TestMethod()]
public void RequestPropertyRequestor_MustNotBeVirtual() {
PropertyInfo[] properties = typeof(Request).GetProperties()
.Where(p => p.GetGetMethod().IsVirtual).ToArray();
Assert.AreEqual(0, properties.Count(p => p.Name == "Requestor"), "Model Code Regenerated - change the Request Entity");
}
Not sure of the accuracy of the reflection code but you get what i mean. This way when the entities are regenerated and you have amended the code, the test fails. early warning system
OR
you could turn off code generation and use POCO's.
Recommended Change
If you don't wanna turn off code gen then modifying the T4 template is the way to go. Just
set the "Code Generation Stategy" to None in the properties of the EDMX designer so that the default generation doesn't occur. This results in no derived DbContext or entity classes
in the EDMX designer, right click on the drawing surface and select "Add Code Generation Item". There should be generators listed there, if not just install one through NuGet. Select the EF5 DbContext one.
Find the T4 template for the entity generation and modify.
You can modify the Entities.tt file. More specifically modify the "AccessibilityAndVirtual" method to handle your specific situation. As this template is specific to your current project you do not have to worry about reuse in other projects. You should be able to selectively define which property names you want to exclude from lazy loading. Happy coding.
if I understand you correctly what you want is .Include("Requestor")
Person person =
context.Persons.Include("Requestor").FirstOrDefault();
this would get a Person and the Requestor in one trip to the db for that query.
Edit:
Looking a bit more, this was assuming you had the Property of Requestor on the Person entity, you can however just change this to the appropriate entity and property.

Is Context.SaveChanges called automatically when an entity that is being tracked changes?

If an entities properties have changed in a controller action and Update/SaveChanges is not called, will that entity be updated automatically?
I am using EF 4.1 with a repository pattern. I handle all CRUD operations in my EfRepository class like this:
public void Update(T entity)
{
try{_context.SaveChanges();}
catch{//do stuff}
}
//etc.
In my application I have an ajax/ActionResult call that gets an entity from the db, performs some basic calculations, and returns a JSON object. To make a long story short I discovered a bug in a static helper I was using in my ActionResult that was changing a property value on my entity and not the JSON-model I was returning.
My action method has no Update methods yet my entity was being updated every time I called this action. Using Sql Profiler I confirmed an update statement that was tailored to update my entity and the one(1) property my buggy static method was changing.
I placed a break point at my Update method in my repository class and even though my entity was being updated by EF, MY Update method was never called. The summary for the interface method 'Find' (which is what I use) in IDbSet says,
Finds an entity with the given primary key values. If an entity with
the given primary key values exists in the context, then it is
returned immediately without making a request to the store. Otherwise,
a request is made to the store for an entity with the given primary
key values and this entity, if found, is attached to the context and
returned. If no entity is found in the context or the store, then null
is returned.
There are some real good example here as well.
I think given my entity was attached, the short answer to my question is 'YES'. But being somewhat new to EF I found this to be a very difficult bug to figure out as it still appears there some things going on under the covers that I could not track down. I hesitated in posting this as a question but thought someone more knowledgeable could expand on my assumed answer of YES and at the bare minimum help someone else who runs across this.
If an entities properties have changed in a controller action and
Update/SaveChanges is not called, will that entity be updated
automatically?
No, ef will only propagate your changes to the database on a SaveChanges call. Save only happens manually (IE you have to explicitly call SaveChanges).
What is really important to understand though is that SaveChanges saves all current modifications to the context. This means if you are sharing a context your changes will be saved when anyone (not just you) calls SaveChanges.

Use Entity Framework to Update only a few properties of a huge class

Scenario:
A huge Patient class/entity with around 100 properties. But in the webpage I only need to display the contact information (only around 10 properties) to update. Do/Can I create a ViewModel to do that?
I have only used ViewModel to read data before. Can it be used to update data?
EDIT:
Okay, to summarize what I have found so far.
Use AutoMapper to map the ViewModel (only contains the properties to be updated) back to the original big EntityClass.
An example is:
[HttpPost]
public virtual ActionResult Edit(EditUser user)
{
var domain = uow.Users.Create();
domain.Id = user.Id;
uow.Users.Update(domain);
AutoMapper.Mapper.Map<EditUser, Example.Core.Data.User>(user, domain);
uow.Save();
return View();
}
Create another entity called PatientSummary in the EDMX model, which only contain the necessary properties. Manually do the mapping in the EDMX designer. Then use this reduced entity for the Patient contact update web page.
Personally, I feel there must be a better way to do that. Any comment?
Yes upon save simply load your object and then use automapper to copy the properties back to your object or manually set them on your EF class.
EF will know which props changed and only send updatea for those changed properties.
I actually posted a couple of questions a little while back on a related topic - question 1 and more specific question 2.
I wasn't a hundred percent happy with the one answer that I got so far on question 2 but the experts seemed to agree that it is a good idea to use view models. For one it saves you from manually making sure that the "other" 90 properties don't get overwritten in the database by the generated UPDATE statement.

DBContext, state and original values

I'm working with ASP.NET MVC3 using EF and Code First.
I'm writing a simple issue tracker for practice. In my Controller I have a fairly standard bit of code:
[HttpPost]
public ActionResult Edit(Issue issue) {
if (ModelState.IsValid) {
dbContext.Entry(issue).State = EntityState.Modified
.....
}
}
Question part 1
I'm trying to get my head around how the dbcontext works -
Before I've set the State on the dbContext.Entry(issue), I assume my issue object is detached. Once I set the state to be modified, the object is attached - but to what? the dbContext or the database? I'm kind of missing what this (attaching) actually means?
Question part 2
For argument's sake, let's say I decide to set the "Accepted" field on my issue. Accepted is a boolean. I start with it being false, I'm setting it to true in the form and submitting. At the point that my object is attached, what is the point of the OriginalValues collection? for example if I set a breakpoint just after setting EntityState.Modified but before I call SaveChanges() I can query
db.Entry(issue).OriginalValues["Accepted"]
and this will give me the same value as simply querying the issue object that has been passed in to the Edit....i.e. it is giving the same result as
issue.Accepted
I'm clearly missing something because the documentation says
"The original values are usually the entity's property values as they were when last queried from the database."
But this is not the case because the database is still reporting Accepted as being false (yeah, I noted the word "usually" in the docs but my code is all pretty much standard generated by MS code so....).
So, what am I missing? what is actually going on here?
The context can work only with attached entities. The attaching means that context know about the entity, it can persists its data and in some cases it can provide advanced features like change tracking or lazy loading.
By default all entities loaded from the database by the context instance are attached to that instance. In case of web applications and other disconnected scenarios you have a new context instance for every processed HTTP request (if you don't you are doing a big mistake). Also your entity created by model binder in HTTP POST is not loaded by that context - it is detached. If you want to persist that entity you must attach it and inform context about changes you did. Setting state to Entry to Modified will do both operations - it will attach entity to the context and set its global state to Modified which means that all scalar and complex properties will be updated when you call SaveChanges.
So by setting state to Modified you have attached the entity to the context but until you call SaveChanges it will not affect your database.
OriginalValues are mostly useful in fully attached scenarios where you load entity from the database and make changes to that attached entity. In such case OriginalValues show property values loaded from database and CurrentValues show actual values set by your application. In your scenario context doesn't know original values. It thinks that original values are those used when you attached the entity.

Resources