Create one-to-one relation without adding reference in one of the tables

  Kiến thức lập trình

I have 2 tables: Company(Id uniqueidentifier, …), Address(Id int,…) and representative entities: Company and Address. They should have relation one-to-one. As I don’t want to have any reference to Company in Address entity I thought of creating join-table CompanyAddress(CompanyId, AddressId).

In mapping, I did the following:

modelBuilder.Entity<Company>(
            entity =>
                {
                     entity.HasOne(c => c.Address)
                          .WithOne(c => c.Company)
                          .HasForeignKey<Address>(c => c.Id);
                }

but receiving error:

The relationship from 'Address.Company' to 'Company.Address' with foreign key properties {'Id' : int} cannot target the primary key {'Id' : Guid} because it is not compatible. Configure a principal key or a set of foreign key properties with compatible types for this relationship.

This issue I cannot resolve without help.

Or, maybe, there is different way of mapping for one-to-one?

LEAVE A COMMENT