gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:20:12 25 4
gpt4 key购买 nike

我有这个:

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; }
}

我的数据库是这样的:

CREATE TABLE [Foo](
[Id] INT,
[Bar_Something] INT NOT NULL,
[Bar_SomethingElse] INT NOT NULL,
)

当我获取数据库上下文时

public class DB: DbContext
{
public DbSet<Foo> Foo { get; set; }
}

Foo.Id 已正确映射,但 Bar 无法映射并出现此错误 System.InvalidOperationException:实体类型“Bar”需要一个主键已定义。

我不想创建 Bar 表并将其 ID 作为 FK 提供给 Foo。如何将列 Bar_SomethingBar_SomethingElse 映射到 Foo.Bar.SomethingFoo.Bar.SomethingElse

最佳答案

EF Core 2.0 及更高版本支持 Owned entity types .默认情况下,这些映射使用 Table splitting .

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

[Owned]
public class Bar
{
public int Something { get; set; }
public int SomethingElse { get; set; }
}

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

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

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

modelBuilder.Entity<Foo>().OwnsOne(p => p.Bar);

关于c# - EF 核心数据库特定列到嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53063181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com