[英]EF Core 3.0.0 - Two one-to-one relations of same type
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).问题:在我添加或更新请求后,它们会覆盖其中一个请求的外键属性(通常,Reminder 的 id 将放置在 RequestId 和 ReminderId 两个字段中)。
Database model:数据库 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:一些测试 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?那么有没有人知道为什么它会这样以及如何让它正常工作?
This looks like a bug, and it repros on EF Core 5.0.5.这看起来像一个错误,它在 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. IE 使用客户端的导航属性而不是请求的属性来关联实体。
And please open an issue here: https://github.com/dotnet/efcore/issues请在此处打开一个问题: https://github.com/dotnet/efcore/issues
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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.