EF Core 3.0.0 - Two one-to-one relations of same type

80 views Asked by At

I'm trying to create two one-to-one releation from one type to another one.

Background: I have a client which sends requests. In a new user story I need to add reminder requests to the client.

Problem: After I add or update the requests, they override the foreign key property of one of the requests (normally the id of Reminder will be placed into both fields RequestId & ReminderId).

Database model:

public class Client
{
    [Key]
    public int Id { get; set; }

    public int? RequestId { get; set; }

    [ForeignKey(nameof(RequestId))]
    public Request Request { get; set; }

    public int? ReminderId { get; set; }

    [ForeignKey(nameof(ReminderId))]
    public Request Reminder { get; set; }
}

public class Request
{
    [Key]
    public int Id { get; set; }

    [InverseProperty(nameof(Client.Request))]
    public Client RequestClient { get; set; }

    [InverseProperty(nameof(Client.Reminder))]
    public Client ReminderClient { get; set; }
}

Some code to test the model:

class Program
{
    static void Main(string[] args)
    {
        using (var context = new Context())
        {
            var client = new Client();

            client = context.Clients.Add(client).Entity;
            context.SaveChanges();

            var request = new Request();
            request.RequestClient = client;

            context.Requests.Add(request);
            context.SaveChanges();

            var reminder = new Request();
            request.ReminderClient = client;

            context.Requests.Add(reminder);
            context.SaveChanges();
        }

        using (var context = new Context())
        {
            var t = context.Clients.ToList();
            var t2 = context.Requests.ToList();
        }
    }
}

Database result:

enter image description here

So has anyone any ideas why it is acting like this and how to get it work properly?

2

There are 2 answers

1
Serge On BEST ANSWER

Try to add these attributes:

public class Client
{
  .....

    [ForeignKey(nameof(RequestId))]
   [InverseProperty("RequestClient")]
    public virtual Request Request { get; set; }

  
    [ForeignKey(nameof(ReminderId))]
     [InverseProperty("ReminderClient")]
    public virtual Request Reminder { get; set; }
}
0
David Browne - Microsoft On

This looks like a bug, and it repros on EF Core 5.0.5. To work around, simplify your code like this:

var client = new Client();

client.Request = new Request();
client.Reminder = new Request();
context.Clients.Add(client);
context.SaveChanges();

IE associate the entities using Client's Navigation properties instead of Request's.

And please open an issue here: https://github.com/dotnet/efcore/issues