【问题标题】:Entity Framework error : "Navigation properties can only participate in a single relationship"实体框架错误:“导航属性只能参与单个关系”
【发布时间】:2020-06-24 14:19:55
【问题描述】:

我的设置类似于下面

public class Component
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public List<ComponentUpdate> Updates { get; set; }
    public ComponentUpdate LastUpdate { get; set; }
}

public class ComponentUpdate
{
    public int Id { get; set; }
    public DateTime Timestamp { get; set; }
    public Component Component { get; set; }
    public string Message { get; set; }
}

我已经设置好了

modelBuilder.Entity<Component>().HasMany(c => c.Updates).WithOne(u => u.Component);
modelBuilder.Entity<ComponentUpdate>().HasOne(u => u.Component).WithOne(c => c.LastUpdate);

但 Entity Framework 抛出错误:

导航属性只能参与单个关系

以上设置有什么问题?我有时想使用导航属性获取最后更新。这似乎是一个 EF 限制...

【问题讨论】:

    标签: c# entity-framework-core ef-core-3.0


    【解决方案1】:

    您必须为每个关系定义一个单独的导航属性,并且还必须为第二个关系定义一个外键:

       public class Component
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Type { get; set; }
            public List<ComponentUpdate> Updates { get; set; }
            public ComponentUpdate LastUpdate { get; set; }
        }
    
    
        public class ComponentUpdate
        {
            public int Id { get; set; }
            public DateTime Timestamp { get; set; }
            public Component Component { get; set; }
            public int SecondComponentId { get; set; }
            public Component SecondComponent { get; set; }
            public string Message { get; set; }
        }
        
         builder.Entity<Component>()
            .HasMany(c => c.Updates)
            .WithOne(u => u.Component);
    
         builder.Entity<ComponentUpdate>()
            .HasOne(u => u.SecondComponent)
            .WithOne(c => c.LastUpdate)
            .HasForeignKey<ComponentUpdate>(x => x.SecondComponentId);
    

    【讨论】:

    • 但这会导致另一个属性具有完全相同的信息,因此它的数据重复只是为了绕过 EF 限制
    • 如果它们始终相同,则不需要一对一的关系。您可以删除`public ComponentUpdate LastUpdate { get;放; }` 来自组件类。
    • 但是我想使用该导航属性来获取有关latest update的信息
    • Updates 列表中的最后一项是您的最新更新,无需为其添加导航属性。
    • 这意味着,如果我有 100 个更新,我应该让所有更新都只更新一次……这是个问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    相关资源
    最近更新 更多