Search code examples
c#entity-frameworkef-code-firstentity-framework-5navigation-properties

How to Model Entity Framework Entity/Mapping With Only One-Way Navigation


Using EF 5, Code First.

I'd like to model my entities such that the navigation properties only exist on one side of the relationship.

So if I have a table Widget, and a table WidgetType:

public class Widget
{
    public int Id { get; set; }
    public int WidgetTypeId { get; set; }
    public WidgetType WidgetType { get; set; }
}

public class WidgetType
{
    public int Id { get; set; }
    //note there is no collection of Widgets here
}

public class WidgetMap : EntityTypeConfiguration<Widget>
{
    public WidgetMap()
    {
        HasKey(t => t.Id);
        //totable, etc.

        HasRequired(t => t.WidgetType); //what else is needed?
    }
}

I will never want to fetch widgets from the perspective of widgetType, so it makes sense (to me anyway) to not have the navigation property on the WidgetType entity.

How do I complete the mapping code noted in the code sample without having to add a property to WidgetType? Is this possible?


Solution

  • As requested in comments, here's my answer.

    You should try:

    HasRequired(t => t.WidgetType).WithRequired().HasForeignKey(t => t.FKField);