I have some domain classes that look something like this, that I want to model with Code First (in EF 4.3).
public class Foo {
// ...
}
public class Bar {
// ...
public Foo Foo { get; set; }
}
public class Baz {
// ...
public Foo Foo { get; set; }
}
In every example I see though, foreign object references are added in the Foo class. Can my Foo class be agnostic of the Bar and Baz class, or do I really need to do something like this?
public class Foo {
// ...
public virtual Bar { get; set; }
public virtual Baz { get; set; }
}
According to this answer, classes do need to have navigation properties. I’m new at Code First, so can anyone explain why this might be the case? Is there a way I can avoid polluting my Foo class like this by using the Fluent API?
It seems weird to me that Foo would need to know about every class that uses it. Is my design simply fundamentally flawed in some way?
The other answer is partly correct.
If you want code-forst to bootstrap your database model with relationships between the tables you’ll have to define at least in one class a navigation property.
The mapping will of course also work without the relationship, but you won’t have the constraints on the database/sql level. Unless you add them with migrations or some other sql-scripts.
Though in your example I am not quite sure what kind of relationship you’re trying to define anyhow. Is that supposed to be a one-to-one relationship?
In that case, Foo doesn’t need to know about any other class that has a reference to it, as answered in your linked question, only one class needs to have it.