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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top