dotnet/efcore

1:1 relationship with ID conventional properties synced on both ends

Closed this issue · 2 comments

I am trying to figure out if EF Core can be set so that it keeps ID properties on both ends of a foreign key in sync. I have a model like this:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CarId { get; set; }
    public Car Car { get; set; }
}

public class Car
{
    public int Id { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
    public int UserId { get; set; }
    public User User { get; set; }
}

I use the fluent API to tell EF Core which entity is the principal one and which is the dependent one:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<User>()
        .HasOne(principal => principal.Car)
        .WithOne(dependant => dependant.User)
        .HasForeignKey<Car>(car => car.UserId);
}

When I do this and then insert:

appDbContext.Users.Add(new User() {
    Name = "John Doe",
    Car = new Car() {
        Make = "Tesla",
        Model = "3",
    },
});

The database ends up in this state (in parentheses are the respective ID property values):

User John Doe (1) has car #1
Car Tesla 3 (1) has user #0

I would like to achieve the dependent ID property to contain the ID of the principal entity after save, so:

User John Doe (1) has car #1
Car Tesla 3 (1) has user #1

I tried to set two FKs, one in each direction, but that didn't help.

Is this possible to achieve using EF Core?

EF Core version: 2.2.2
Database Provider: SQL Server
Operating system: Windows
IDE: CLI

This looks like a many-to-many relationship. (That is, a user can have many cars, and a car can have many users.) If so, check out many-to-many mapping in the docs.

I don't think this is a many to many relationship, because while there can be multiple cars associated with one user, only one of those cars can be set to CarId on the user entity. So it can be 1:N for user:car and 1:N for car:user but in both cases there are dangling entities in the N. And this is what I am looking to prevent - to have EF ensure for me that this always stays 1:1. Is that possible?