5

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?

Community
  • 1
  • 1
Eric
  • 5,842
  • 7
  • 42
  • 71

2 Answers2

2

Your problem here will be requirement for one-to-one relation. One-to-one relation in EF is mapped through primary keys. You choose principal entity and the dependent entity must have FK on its PK - they must have same PK value to be related. The reason is missing support for unique keys.

Once you accept this limitation you can simply use your model and map it like:

modelBuilder.Entity<Bar>()
            .HasRequired(b => b.Foo)
            .WithOptional();

modelBuilder.Entity<Baz>()
            .HasRequired(b => b.Foo)
            .WithOptional();
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
1

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.

mfussenegger
  • 3,931
  • 23
  • 18
  • Thanks, this clarified my misunderstanding. I hastily misinterpreted the other answer as saying that `Foo` would have to have the navigation property. – Eric Aug 23 '12 at 18:10