Marcelo De Zen
Marcelo De Zen

Reputation: 9497

Map an optional one-to-one in EF6 Code-first

I've seem many similar questions about one-to-one mapping, yet I'm stuck with this particular case.

Considering the following:

// model
class Parent
{
    public int ParentId { get; set; }
    // children   
    public virtual ICollection<Child> Children { get; set; };
    // active child
    public int ActiveChildId { get; set; }
    public virtual Child ActiveChild { get;set; }
}

class Child
{
    public int ChildId { get; set; }
    public int ParentId { get; set; }
    public virtual Parent Parent { get; set; }
}

So the parent has a collection of Child entities, but it has also a FK to one its children. The problem is that I can't find a way to tell to EF6 fluent API to map Parent.ActiveChild property to use Parent.ActiveChildId foreign key.

// map
class ParentMap : EntityTypeConfiguration<Parent>
{
    public ParentMap()
    {
        // parent <>=== children 
        HasMany(parent => parent.Children)
            .WithRequired(child => child.Parent)
            .HasForeignKey(child => child.ParentId);

        // parent ---> child
        HasOptional(parent => parent.ActiveChild) // ???? no way to tell EF to use IdActiveChild as FK for this property.
    }
}

Upvotes: 0

Views: 742

Answers (1)

Rob Tillie
Rob Tillie

Reputation: 1147

First, you'll want to make your id property optional:

public int? ActiveChildId { get; set; }

If you're using the default conventions this will work. In your case, when using a map, HasForeignKey is not available for an optional relationship. You can solve this by using the HasMany method without specifying the other side, like this:

HasOptional(parent => parent.ActiveChild)
    .WithMany()
    .HasForeignKey(parent => parent.ActiveChildId)

For more background, you can view the complete explanation here: http://patrickdesjardins.com/blog/how-to-setup-entity-framework-code-first-to-have-only-one-side-0-to-1-relationship

Upvotes: 2

Related Questions