Massey
Massey

Reputation: 1127

How to create one to zero or one relationship in Entity Framework code-first?

I am trying to create a one to zero or one relationship between the Institution and Address tables. I am essentially expecting the AddressId column will be included in the Institution table after the relationship is established.

This is my code:

public class Institution
{
    public int InstitutionId { get; set; }
    public string Name { get; set; }

    //1 to 1 with Address
    public virtual Address Address { get; set; }

    //one--to-many with Professor
    public virtual IList<Professor> Profesors { get; set; }
}

public class Address
{
    public int AddressId { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public int StateId { get; set; }
    public int CountryId { get; set; }
    public string ZipCode { get; set; }

    public virtual Institution Institution { get; set; }
}

In the context class:

modelBuilder.Entity<Institution>()
            .HasOptional(i => i.Address)
            .WithRequired(ad => ad.Institution);

When I see the database diagram I see a relationship established between these two tables - with a yellow colored key on both ends of the line - but neither the AddressId column is included in the Institution table nor the InstitutionId is included in the Address table.

Thanks

Upvotes: 2

Views: 2128

Answers (1)

Morteza Manavi
Morteza Manavi

Reputation: 33206

Basically your intention is to create a One-to-One Foreign Key Association while EF is giving you a Shared Primary Key Association because well, EF 6 does not support the former and Shared Primary Key Association is the only association type EF 6 supports when it comes to 1:1 entity relationships.

Your options apart from what you have right now are:

  1. You can work around this and create a unidirectional one to many association from Address to Institution and then create a unique constraint on AddressId FK on Institution table. SQL Server will see this relationship as a 1:1 while your object model sees an Address on Institution object but (of course) this option won't work for you if you want to also see a Institution on Address object (basically if you need a bidirectional 1:1 association). If you are interested in this option then I explain this workaround in here.

  2. I kept saying EF 6 in the lines above because If you can upgrade then EF Core (formerly EF 7) supports One-to-One Foreign Key Associations because of its new support for alternate keys. Basically it means it now supports unique constraints which is essential for One-to-One Foreign Key Associations.

Upvotes: 2

Related Questions