Hi,
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