【问题标题】:Entity Framework - include ComplexType实体框架 - 包括 ComplexType
【发布时间】:2017-12-21 16:04:48
【问题描述】:

我在 EF Core 2.0 中有一个实体类:

public class Component : BaseModel
{
    [Required]
    public string Name { get; set}
    public virtual ICollection<ComponentInstance> ComponentInstances { get; set; }
    public virtual Title Title {get ; set;}
}

还有另一个ComplexType 类:

[ComplexType]
public class Title
{
    public string Text { get; set; }
    public string Color { get; set; }
    public string BackgroundColor { get; set; }
}

运行此代码:

var component = _dbContext.Company
                          .Where(x => x.Id == componentId)
                          .Include(x => x.Title)
                          .FirstOrDefault();

抛出异常:

属性“标题”不是实体类型“组件”的导航属性。 'Include(string)' 方法只能与 '.' 一起使用。导航属性名称的分隔列表。

【问题讨论】:

  • 请提供确切的例外情况。
  • @brunttoast1 我已经尝试过了,但它仍然给出相同的异常属性“标题”不是实体类型“组件”的导航属性。 'Include(string)' 方法只能与 '.' 一起使用。导航属性名称的分隔列表。
  • 这会更好地帮助你:stackoverflow.com/questions/46838328/…

标签: c#


【解决方案1】:

如果您仍在苦苦挣扎,您需要在您的班级中添加[ForeignKey("")]。 像这样:

public class Component : BaseModel
    {

        [Required]
        public string Name { get; set}
        public virtual ICollection<ComponentInstance> ComponentInstances { get; set; }
        [ForeignKey("Title")]
        public Title Title {get ; set;}
    }

【讨论】:

  • 但是 Title 类不是我的实体,它是一个 ComplexType,也没有任何主键.. 你认为它会起作用吗?
  • 这是一个问题,因为如果不定义外键,您将无法执行该操作。
【解决方案2】:

最可能的问题是在您的Component 类中,Title 属性未标记为virtual。

如果不是virtual 实体框架不能override 它,然后将忽略它,并且不将其视为具有上下文的实体。

现在即使你把它标记为虚拟,也不一定意味着实体框架会把它识别为实体,所以在这种情况下你需要指定与Entity Framework's Fluent API的关系

如果Component类与实体框架的关系是明确的,基于Convention over Configuration,就不需要显式声明与fluent API的关系了。

您显然还需要在您的类上具有从 DbContext 类继承的 DbSet&lt;Component&gt; 和 DbSet&lt;Title&gt; 属性

【讨论】:

  • 我的 DbContext 类型类中有 DbSet,并且在 Title 之前也存在 vitual
  • @AsifKhan 在您的示例代码中没有虚拟?
  • 是的,它不存在,但在您发表评论后,我也尝试使用 virtual
  • @AsifKhan 我 100% 肯定您的问题是实体框架没有将 Title 识别为 Component 类上的实体。因此,您肯定需要添加虚拟,将其保留在那里,然后确保通过 Fluent API 的约定将 Title 正确配置为 EntityFramework 的实体。如答案所述,仅将其标记为虚拟可能还不够。
  • @Gerrie Pretorius 我明白了,但问题是我的项目在 EntityFramework 中,然后我迁移到 ef core.in EntityFramework Title 只是一个 ComplexType 类,但不是它在没有它的情况下可以正常工作的实体延迟加载..但我想知道在 ef core 中是否有可能,如果可能的话,我该怎么做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 2013-06-21
  • 2012-05-01
  • 2017-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多