Entity Framework 6 One-Way relationship using Code First

code-first ef-code-first entity-framework entity-framework-6

Question

I have the following scenario:

  1. Color Class

    public int ID
    {
        get;
        set;
    }
    
    public string Name
    {
        get;
        set;
    }
    
    public string Hex
    {
        get;
        set;
    }
    
  2. Widget Class

    public int ID
    {
        get;
        set;
    }
    
    public int HeaderBackgroundColorID
    {
        get;
        set;
    }
    
    public Color HeaderBackgroundColor
    {
        get;
        set;
    }
    

Using Code-First, I am trying to create a one-way relationship between Widget to Color classes with the HeaderBackgroundColor / HeaderBackgroundColorID Fields.

normally i would do this in the config class:

this.HasOptional(r => r.HeaderBackgroundColor )
    .WithMany(m => m.Widgets)
    .HasForeignKey(fk => fk.HeaderBackgroundColorID);

but i am not intrested in adding a Widgets collection to the Color class. tried this:

this.HasOptional(r => r.HeaderBackgroundColor )
    .WithMany()
    .HasForeignKey(fk => fk.HeaderBackgroundColorID);

but that throws a validation error.

What's the way to do this right?

1
6
3/24/2014 11:05:38 PM

Accepted Answer

You are getting an error because HeaderBackgroundColorId is a non-nullable int, so it cannot be optional.

All you need to do to achieve what you're looking for is to turn the foreign key into a nullable int...

public int? HeaderBackgroundColorID { get; set; }

Because you named the foreign key to match the navigation property (HeadBackgroundColorId and HeaderBackgroundColor) which follows Code First conventions, you do not need to create any explicit mappings. Simply making the above change will make the relationship optional.

5
3/25/2014 5:07:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow