Entity Framework 4 and validating non-persisted objects in relation collections
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.Entity开发者_开发百科1s.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
DataContext.Entity1s.Add(MyEntity1);
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.
Cardinality of your relationships is part of your model and does not require separate validation. If you require 1..* instead of 0..*, then define the model that way and the EF will validate it for you.
I'd consider first using a simplified saving that would only save your current (game?) state and not all your Entity System objects. Like: "player is at level @123,456 items Foo, Bar".
The other way could be to serialize and then deserialized your objects. Start with a root object, and during the serialization, also serialize all dependencies. This option can be very complex, especially with opened files, conenxions, and other elements that are not serializable.
精彩评论