Entity Framework 核心:具有导航属性的自有类型

Entity Framework Core: Owned type that has navigation properties

我有一些 classes:

public class Project 
{
     public TimeLine TimeLine { get; set; };
}

public class TimeLine 
{
     public ICollection<TimeLinePhases> TimeLinePhases { get; set; };
}

public TimeLinePhase 
{
}

class Project 拥有 TimeLine,这一切都正常,直到我指定 TimeLineTimeLinePhase 之间的导航。

Fluent API 指定 TimeLine 的代码拥有:

  builder.Owned<TimeLine>();
  builder.entity<Project>().OwnsOne(p => p.TimeLine);

我收到这个错误:

InvalidOperationException: Unable to determine the relationship represented by navigation 'TimeLine.TimeLinePhase' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

然后我指定 TimeLineTimeLinePhase 之间的关系,如下所示:

builder
        .Entity<TimeLine>()
        .HasMany(t => t.TimeLinePhase)
        .WithOne()
        .IsRequired(false);

但现在我得到这个错误:

The entity type 'TimeLine' cannot be configured as non-owned because it has already been configured as a owned. Use the nested builder in OwnsOne or OwnsMany on the owner entity type builder to further configure this type

如何将 TimeLine 作为拥有的类型,并且仍然具有 TimeLineTimeLinePhases 之间的关系?

我简单搜索了一下,找到了答案。似乎不允许配置具有集合的自有类型。问题是拥有类型不能充当集合的主要实体

请参阅 AjVickers 在此 GitHub 页面上的评论:https://github.com/dotnet/efcore/issues/27175

似乎需要重新设计数据结构。

尝试显式创建关系

public class TimeLine 
{
    [InverseProperty(nameof(TimeLinePhase.TimeLine))]
     public ICollection<TimeLinePhases>? TimeLinePhases { get; set; };
}

public TimeLinePhase 
{
   
        [Key]
        public int Id { get; set; } 

         public int? TimeLineId {get;set;}

        [ForeignKey(nameof(TimeLineId))]
        [InverseProperty("TimeLinePhases")]
        public virtual TimeLine? TimeLine {get; set;}
}