I am working on a new project that makes use of Entity Framework. I was in love with relationship inverses, having navigation properties on both types would make my life really easier.
Problem is: our project manager thinks that using this facility may lead to mistakes and thus is advising us not to use it.
Let’s say we have Category and Product:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
He says that one can, by mistake, set productZ.Category to categoryX and then do a categoryY.Products.Add(productZ), for example. Then what relationship will be persisted when we save the context? The last one? Ok, what if the first one was the correct category? And that this kind of error is hard to debug (which I agree).
I don’t think this scenario can happen but I really respect his opinion, he’s way more experienced than me, but I really want to convince him to let us have bidirectional navigation properties and the only argument I have is: if everyone is doing it then it cannot be this bad. 🙂
Can you guys help me with some more solid arguments?
One can also write unit test to validate that code sets expected relations. You can always make mistake and removing navigation property is not a solution to avoid the problem. The solution is to validate that your code does what is expected = testing and code coverage.
What you ask is more about designing your classes – not about mistakes. Is it meaningful to have navigation properties on both sides? Are you adding product to category or assigning category to product? Do you need to offer both ways? Can product exists without category? Are you handling products and categories separately or are they aggregate? Based on answers to these questions you can sometimes find that navigation property on one side of relation is not necessary.