Individually in EF, only one foreign key

I am trying to build a 1-1 relationship - the Tenant has 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 would expect both models to have a foreign key ... why is this not so?

+4
source share
1 answer

One-to-one relationships with both ends having the required foreign keys cannot exist in a relational database. If you need a URL entry to save a new Tenant entry, but you need a Tenant entry to create this URL entry, where do you start?

, , . , Entity Framework EntityException, , , , .
, .

, , "--" . , , "--" .

+6

Source: https://habr.com/ru/post/1523548/


All Articles