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:
So has anyone any ideas why it is acting like this and how to get it work properly?
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; }
}