Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 851
Phil Sandler Avatar asked May 29 '13 15:05

Phil Sandler


1 Answers

I know there is an accepted answer, but the above solution didn't work for me and I had to tweak it some.

I'm using Entity Framework 6 and had a similar issue. I had a table called BaseEntity that had a CreatedByID field that pointed to my UserAccount table.

This created an ICollection of type BaseEntity in my UserAccount class. I was able to resolve this by using the following code in my BaseEntity mapping:

this.HasOptional(t => t.UserAccount)
    .WithMany()
    .HasForeignKey(t => t.CreatedByID);

I was then able to remove the collection of BaseEntity from the UserAccount class which created a uni-directional one-to-many mapping in EF6.

The UserAccount entry is optional because UserAccount inherits from BaseEntity. Make sure to use HasRequired() if this is a required attribute in your model.

like image 110
masterwok Avatar answered Oct 26 '22 18:10

masterwok