I hadn't found a good answer to my question on using ExecuteSqlCommand safely in entity framework until I came across Julia Lerman's excellent book 'Programming Entity Framework: DbContext'.
She covers the use of ExecuteSqlCommand (page 226) but most importantly she mentions using the Reload command after ExecuteSqlCommand to update the local (page 138). That updates the in-memory entity from the database. You use it as follows:
After a long search and readings, I finally figured what I was intending to do. I was lucky creating and saving N-Level deep object graph wasn't as hard as Updating those Objects. Anyways, after reading Danny Varod's comment, I decide to go back and read more on DbContext. Below is what I was trying to do, also I apologize I am using the same method to save new objects:
public void SaveTeam(Team team)
{
if (team.Id == 0)
{
context.Teams.Add(team);
}
else if (team.Id > 0)
{
//This Updates N-Level deep Object grapgh
var currentTeam = context.Teams
.Include(c => c.TeamContact)
.Include(a => a.TeamContact.TeamAddress)
.Single(t => t.Id == team.Id);
context.Entry(currentTeam).CurrentValues.SetValues(team);
currentTeam.TeamContact.TeamAddress = team.TeamContact.TeamAddress;
currentTeam.TeamContact = team.TeamContact;
}
context.SaveChanges();
}
You can provide conditional validation using the Entity Framework by overriding DbEntityValidationResult in the DbContext. When this validation occurs in the DbContext you can access other entities. When validating a contact you can check the company too. For example:
protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
var result = base.ValidateEntity(entityEntry, items);
ValidateContact(result);
return result;
}
private void ValidateContact(DbEntityValidationResult result)
{
var contact= result.Entry.Entity as Contact;
if (contact!= null && contact.ContactId != 0)
{
// Add validation code here, such as:
if(!string.IsNullOrEmpty(contact.Company.Name){
result.ValidationErrors.Add(
new DbValidationError(
"Contact",
"Company name cannot be null or empty when validating contacts.")
);
}
}
}
See Julia Lerman's Programming Entity Framework: DbContext http://www.amazon.com/Programming-Entity-Framework-Julia-Lerman/dp/1449312969 for more details.
I've found a number of questions that compare DbContext vs.
ObjectContext. But most of these are from 2010, or early 2011.
If you just want to replace ObjectContext + EDMX with DbContext + EDMX, the comparison is still the same. DbContext is a wrapper around ObjectContext and its feature set didn't grow up except with respect to those features related to Code First and Migrations.
I realize that DbContext is more compact in that it exposes fewer
properties. This suggests to me that I should migrate from
ObjectContext.
Yes, it is more compact and it simplifies most common tasks that you have to do with the context. For more complex tasks, you can still convert a DbContext instance to an ObjectContext instance through IObjectContextAdapter.
But, if I do this migration, will I give up any capabilities? For
example, I've read that DbContext doesn't have the STE (Self-tracking
entities) capability. Does this still hold true and is it a concern?
STE was created for ObjectContext and I don't think it was ported to DbContext, but you can try to implement this capability yourself.
STEs are just a template with an idea to solve some problem. It appeared as a good theoretical solution but it wasn't very well accepted by the developer community because the solution is not very good for real world scenarios. It is also the reason why other more important features are being developed instead of improving or porting the template.
In general it is what you have to do. You must tell EF about each change you want to perform when attaching detached object graph. I don't say that your code cannot be simplified but you will still have to deal with every entity and setting its state if you want it to be added or modified.
Here is little bit older but still valid answer about the topic - in short nothing has changes since I wrote it, only new DbContext API was created which still sits on top of the old API. The best description of this topic I have seen so far is in book Programming Entity Framework: DbContext.
The reason is that including a foreign key property tells Entity Framework to use Foreign Key Association, which is simpler than using the so-called Independent Association when you need to update the relationship, i.e., changing the order from one customer to another in your example. With foreign key association, all you need to do is changing the CustomerId. Without the CustomerId foreign key, you need more steps. The independent association uses the ObjectStateManager that is explained Code First: Independent associations vs. Foreign key associations? The ObjectStateManager is complex and is not even exposed from DbContext API.
I hadn't found a good answer to my question on using ExecuteSqlCommand safely in entity framework until I came across Julia Lerman's excellent book 'Programming Entity Framework: DbContext'.
She covers the use of ExecuteSqlCommand (page 226) but most importantly she mentions using the Reload command after ExecuteSqlCommand to update the local (page 138). That updates the in-memory entity from the database. You use it as follows:
This is exactly what I needed. Thanks Julia.
I my opinion Julia Lerman's DbContext book is a must for anyone planning a real-life application using Code First.
After a long search and readings, I finally figured what I was intending to do. I was lucky creating and saving N-Level deep object graph wasn't as hard as Updating those Objects. Anyways, after reading Danny Varod's comment, I decide to go back and read more on DbContext. Below is what I was trying to do, also I apologize I am using the same method to save new objects:
You can provide conditional validation using the Entity Framework by overriding DbEntityValidationResult in the DbContext. When this validation occurs in the DbContext you can access other entities. When validating a contact you can check the company too. For example:
See Julia Lerman's Programming Entity Framework: DbContext http://www.amazon.com/Programming-Entity-Framework-Julia-Lerman/dp/1449312969 for more details.
Your question does not start off well because a single Google query will give you an answer for this. There is an excellent book about DbContext itself — it doesn't contain anything about the Code First approach, but I guess that is really not the point of your question.
If you just want to replace
ObjectContext
+ EDMX withDbContext
+ EDMX, the comparison is still the same.DbContext
is a wrapper aroundObjectContext
and its feature set didn't grow up except with respect to those features related to Code First and Migrations.Yes, it is more compact and it simplifies most common tasks that you have to do with the context. For more complex tasks, you can still convert a
DbContext
instance to anObjectContext
instance throughIObjectContextAdapter
.STE was created for
ObjectContext
and I don't think it was ported toDbContext
, but you can try to implement this capability yourself.STEs are just a template with an idea to solve some problem. It appeared as a good theoretical solution but it wasn't very well accepted by the developer community because the solution is not very good for real world scenarios. It is also the reason why other more important features are being developed instead of improving or porting the template.
For Linq-to-entities you can check MSDN:
Sources for EFv4.1 code first are:
As I know there is no book covering EFv4.1 yet.
Edit (May 2012): There are two books about EFv4.2 (Code first / DbContext API) now:
In general it is what you have to do. You must tell EF about each change you want to perform when attaching detached object graph. I don't say that your code cannot be simplified but you will still have to deal with every entity and setting its state if you want it to be added or modified.
Here is little bit older but still valid answer about the topic - in short nothing has changes since I wrote it, only new DbContext API was created which still sits on top of the old API. The best description of this topic I have seen so far is in book Programming Entity Framework: DbContext.
According to Julia Lerman's book: Programming Entity Framework: DbContext, the difference lies at the difficulty of updating the navigation property. In page 85, She suggests "If there is one thing you can do to make your life easier in N-Tier scenarios, it’s to expose foreign key properties for the relationships in your model." The book includes samples for both scenarios.
The reason is that including a foreign key property tells Entity Framework to use Foreign Key Association, which is simpler than using the so-called Independent Association when you need to update the relationship, i.e., changing the order from one customer to another in your example. With foreign key association, all you need to do is changing the CustomerId. Without the CustomerId foreign key, you need more steps. The independent association uses the ObjectStateManager that is explained Code First: Independent associations vs. Foreign key associations? The ObjectStateManager is complex and is not even exposed from DbContext API.