Search code examples
c#entity-frameworkfluent-entity-framework

If I have a non standard Foreign Key name do I need to manually setup both sides of a relationship?


I am working on a Database First project and I am using a EntityTypeConfiguration class to set up Fluent definations of my models (Used the "Reverse Engineer Code First" tool to get the initial classes).

In one set of my classes I have a non standard key n that associates two objects in a one to many relationship. Here is a example set of classes.

class Foo
{
    public int FooId {get; set;}
    public string SomeData {get; set;}
    public virtual ICollection<Bar> Bars {get; set;}
}

class Bar
{
    public int BarId {get; set;}
    public int ThisIntPointsToFooId {get; set;}
    public virtual Foo Foo {get; set;}
}

When I create EntityTypeConfiguration<Foo> and EntityTypeConfiguration<Bar> do I need to define the relationship from both sides or can I do it from just one side and the other will pick it up?

class FooMap : EntityTypeConfiguration<Foo>
{
    //(Snip other members)

    this.HasMany(t => t.Bars).WithRequired(t => t.Foo).HasForeignKey(t => t.ThisIntPointsToFooId);
}

class BarMap : EntityTypeConfiguration<Bar>
{
    //(Snip other members)

    this.HasRequired(t => t.Foo).WithMany(t => t.Bars).HasForeignKey(t => t.ThisIntPointsToFooId);
}

Solution

  • One mapping is enough - and actually better in my opinion. If you want to change something - like making the FK nullable and the relationship optional (HasOptional/WithOptional) or adding WillCascadeOnDelete(false) to the relationship - you don't have to care about two mappings but only change one place.