EF 核心数据库特定列到嵌套对象

7 c# entity-framework-core .net-core

我有这个:

public class Foo
{
    public int Id { get; set; }
    public Bar Bar { get; set; }
}

public class Bar
{
    public int Something { get; set; }
    public int SomethingElse { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的数据库是这样的:

CREATE TABLE [Foo](
    [Id]                 INT,
    [Bar_Something]      INT    NOT NULL,
    [Bar_SomethingElse]  INT    NOT NULL,
)
Run Code Online (Sandbox Code Playgroud)

当我获得数据库上下文时

public class DB: DbContext
{
    public DbSet<Foo> Foo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Foo.Id已正确映射但Bar无法映射此错误System.InvalidOperationException : The entity type 'Bar' requires a primary key to be defined.

我不想创建 Bar 表并将其 id 作为 FK 给 Foo。如何将列Bar_Something和映射Bar_SomethingElseFoo.Bar.SomethingFoo.Bar.SomethingElse

Pan*_*vos 7

EF Core 2.0 及更高版本支持拥有的实体类型。默认情况下,这些是使用Table splitting映射的。

在 EF Core 2.1 中,您可能只需要将[Owned]属性添加到Bar,即:

[Owned]
public class Bar
{
    public int Something { get; set; }
    public int SomethingElse { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

拥有的类型的属性将映射到名为 的同一个表中的字段Property_OwnedProperty。在这种情况下,它将是Bar_SomethingBar_SomethingElse

看起来有人在设计表格时考虑了这些要求。

在 EF Core 2.0 中,您需要在上下文配置中指定所拥有的类型:

modelBuilder.Entity<Foo>().OwnsOne(p => p.Bar);
Run Code Online (Sandbox Code Playgroud)