SB2055
SB2055

Reputation: 12912

One-to-one in EF only producing one Foreign Key

I'm attempting to build a 1-1 relationship - a Tenant has a Url, and vice versa:

Models

public class Tenant {

    [Key]
    [Required]
    public int TenantId { get; set; }

    public string Name { get; set; }

    public virtual Url Url { get; set; }
    public int UrlId { get; set; }

}

public class Url {

    [Key]
    [Required]
    public int UrlId { get; set; }

    public string Name { get; set; }

    public virtual Tenant Tenant { get; set; }
    public int TenantId { get; set; }
}

Configs

public class UrlConfiguration : EntityTypeConfiguration<Url> {
    public UrlConfiguration() {

        HasKey(s => s.UrlId);

    }
}
public class TenantConfiguration : EntityTypeConfiguration<Tenant>
{
    public TenantConfiguration() {
        HasRequired(s => s.Url).WithRequiredPrincipal(s => s.Tenant);
    }
}

Result:

enter image description here

I'd expect there to be a foreign key on both models... why is this not the case?

Upvotes: 4

Views: 118

Answers (1)

Olaf
Olaf

Reputation: 899

A one-to-one relationship with both ends having required foreign keys cannot exist in a relational database. If saving a new Tenant record requires a URL record, but in order to create that URL record, that URL requires a Tenant record, where will you begin?

Even though on a database level it can't practically exist, this model will still work. From my experience, Entity Framework will enforce the dependency on application level, and will throw an EntityException when it detects that one of the entities you're trying to save has no relationship to one of the other.
It creates this database model so that it can still save your entities, and enforce relationships on an application level.

No, this isn't nice on a database level as the one-to-one constraint won't be enforced there. If you need the database constraints as well, consider merging the tables or redesigning your data structures so that a one-to-one relationship isn't necessary.

Upvotes: 6

Related Questions