1

I have the following classes.

class Zero
{
    One One { get; set; }
    int OneId { get; set; }
}

class One
{
    Zero Zero { get; set}
}

modelBuilder.Entity<Zero>()
        .HasRequired(e => e.One)
        .WithOptional(a=>a.Zero)
        .HasForeignKey(e => e.OneId);//<--error

there is no HasForeignKey after WithOptional, only after WithMany

What can I do to get the same results ?

ihisham
  • 248
  • 1
  • 10
  • 1
    `HasForeignKey` is missing for a purpose (not supported for `one-to-one` relationships). Do you really need separate FK in `Zero`? EF by default uses shared primary key association for this type of relationship, i.t. the `Zero` PK will also be FK. If you are not constrained to existing database, I would recommend using that strategy. – Ivan Stoev May 15 '17 at 15:26
  • I need the FK in my class Zero – ihisham May 15 '17 at 15:54
  • 1
    Ok, then the only option you have is to create independent association, i.e. without explicit FK property. Remove the `int OneId { get; set; }` and use `.Map(m => m.MapKey("OneId"))` fluent API. – Ivan Stoev May 15 '17 at 16:42

1 Answers1

1

In EF 6.X you can take a lok to this stackoverflow post Implementing Zero Or One to Zero Or One relationship in EF Code first by Fluent API

In EF Core you can try this


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity()
                .HasOne(p => p.Link)
                .WithOne(i => i.UrlProvider)
                .HasForeignKey(b => b.UrlProviderId);
        }
Community
  • 1
  • 1
Hicham Bouchilkhi
  • 682
  • 10
  • 29