gpt4 book ai didi

entity-framework-core - Entity Framework Core OwnsOne 创建单独的表,而不是像预期的那样将属性添加到同一个表

转载 作者:行者123 更新时间:2023-12-05 04:04:42 27 4
gpt4 key购买 nike

我认为 Entity Framework Core 拥有的类型默认会添加到与其所有者相同的表中。但我在迁移中没有看到这一点。

有人会在这里给我线索吗?

有没有办法通过将 Name 属性直接添加到 Person 表来获得所需的迁移?

public class Person
{
public Name Name { get; set; }
}

public class Name
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

public class PersonConfiguration : IEntityTypeConfiguration<Person>
{
public void Configure(EntityTypeBuilder<Person> person)
{
person.OwnsOne(p => p.Name);
}
}

dotnet ef 迁移添加 DidNotSeeThatComing结果

public partial class DidNotSeeThatComing : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Name",
columns: table => new
{
FirstName = table.Column<string>(type: "varchar", nullable: true),
LastName = table.Column<string>(type: "varchar", nullable: true),
PersonId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Name", x => x.PersonId);
table.ForeignKey(
name: "FK_Name_Person_PersonId",
column: x => x.PersonId,
principalTable: "Person",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
);
}
}

最佳答案

我自己无意中用这个配置代码创建了这个

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
entity.Relational().TableName = entity.Name;
}
}

这是我正在使用的解决方法

[Owned] // Microsoft.EntityFrameworkCore
public class Name { ... }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
if(!entity.ClrType.GetCustomAttributes().OfType<OwnedAttribute>().Any())
{
entity.Relational().TableName = entity.Name;
}
}
}

关于entity-framework-core - Entity Framework Core OwnsOne 创建单独的表,而不是像预期的那样将属性添加到同一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52189885/

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