What is the best practice with regard to the Entity Framework and validating new objects prior to persisting them (or in other words calling .SaveChanges()) when the new object may rely on either persisted objects or other new objects?
For example, consider the following:
Entity1 MyEntity1 = new Entity1();
MyEntity1.Name = "Hornblower";
DataContext.Entity1s.Add(MyEntity1);
.... Other code ....
Entity2 MyEntity2 = new Entity2();
MyEntity2.Entity1s.Add(MyEntity1);
.... Other code ....
// Validate that MyEntity2 has at least 1 Entity1 relationship
if (MyEntity2.Entity1s.Count() > 0 )
{
// Valid - save it
DataContext.SaveChanges();
} else {
// Invalid - handle it
}
In the above pseudo code, would this be a valid and correct method of validating the required conditions – can the .Count() be relied upon to return both persisted MyEntity1s and non-persisted MyEntity1s, and thus in the above case cause the validation to succeed?
Or should I be persisting MyEntity1 prior to attaching it to MyEntity2?
Regards
Moo
Your code is a bit dis-jointed.
You have attached MyEntity1 to the ObjectContext by calling
but have not attached (or have not shown in the example) MyEntity2 to the Context.
That being besides the point, the short answer is Yes. Your validation will hold true and will pass as being valid.
Reasoning:
Entity manipulation is independent of Object Context. When adding or removing associations from entities, changes are reflected on the entities regardless of its state in relation to the Object Context that manages it.
Pitfall
Your real problem will be when calling SavingChanges() to the Context. When trying to persist entities (namely entity graphs), you must be aware that the context is very sensitive to Object States. This means you cannot persist an entity graph of mixed attached and detached entities.