我有两张桌子,Accounts张和Reservations张.它们之间是一对多关系(一个帐户可以有多个预订),因此预约表有AccountId列.

public class Account 
{
    public Guid Id { get; set; }
    ...
    [JsonIgnore] 
    public List<Reservation> Reservations { get; set; } = new List<Reservation>();
}

public class Reservation 
{
    ...
    public Guid AccountId { get; set; }

    [JsonIgnore] 
    public Account Account { get; set; }
}

实体框架本身就解决了这一问题,我在OnModelCreating()中没有任何关于这个关系的具体内容.

现在我需要添加另一个类似的关系,当"父"帐户代表"常规"帐户创建预订时.因此,预订需要一个同时指向客户的ParentAccountId列.原始关系需要保持不变.

我在预订类中添加了以下内容:

public Guid? ParentAccountId { get; set; }

[JsonIgnore] 
public Account? ParentAccount { get; set; }

现在EF不再能够单独重新锁定关系,当我try 重建数据库时,我收到以下错误:

System.InvalidOperationException:无法确定由类型为"List"的导航"Account.Reservations"表示的关系.手动配置关系,或使用"[NotMapped]"属性或通过使用"OnModelCreating"中的"NotityTypeBuilder.Ignore"忽略此属性.

我如何才能正确配置它?

推荐答案

您可以使用FLUENT API来"解释"您的意图:

modelBuilder.Entity<Account>()
    .HasMany(a => a.Reservations)
    .WithOne(r => r.Account);
modelBuilder.Entity<Reservation>()
    .HasOne(r => r.ParentAccount)
    .WithMany();

请注意,您不能将多个关系映射到同一集合属性(因此会出现原始错误),如果您希望公开它,则需要声明一个新的关系:

public class Account 
{
    // ...

    [JsonIgnore] 
    public List<Reservation> ReservationsAsParent { get; set; } = new List<Reservation>();
}

和映射:

modelBuilder.Entity<Account>()
    .HasMany(a => a.Reservations)
    .WithOne(r => r.Account);        
modelBuilder.Entity<Account>()
    .HasMany(a => a.ReservationsAsParent)
    .WithOne(r => r.ParentAccount);

Csharp相关问答推荐

HttpContext. RequestAborted当Android APP失go 连接时未取消

使用LayoutKind在C#中嵌套 struct .显式

在多对多关系上不删除实体

如果存在对CodeAnalysis.CSharp的引用,则不能引用netStandard2.0库

为什么任务需要在内部使用ManualResetEventSlim?

只有第一个LINQ.Count()语句有效

JsonSerializer.Deserialize<;TValue>;(String,JsonSerializerOptions)何时返回空?

Rider将.NET安装在哪里

如何使用MoQ模拟Resources GroupCollection?

.NET 8 DI GetServices<;对象&>不工作

在DoubleClick上交换DataGridViewImageColumn的图像和工具提示

使用C#和.NET 7.0无法访问Cookie中的数据

C#LINQ子字符串

JsonPath在Newtonsoft.Json';S实现中的赋值

在同一个捕获中可以有多种类型的异常吗?

忽略Visual Studio代码中的StyleCop规则

如何使用IHostedService添加数据种子方法

如何在绑定到数据库的datagridview中向上或向下移动行

当`JToken?`为空时?

使用生产环境调试我的应用程序的快速方法