gpt4 book ai didi

sql-server - EF Core 添加迁移生成带有 ColumnName1 的额外列

转载 作者:行者123 更新时间:2023-12-05 02:08:24 24 4
gpt4 key购买 nike

当我生成迁移时,我有以下实体,它创建了两个名为 RestrictedCategoryId 和 RestrictedCategoryId1(FK) 的列。 FK 只生成一列怎么解决?

注意:我需要每个实体中的 OrderId。

`C#

public class Order
{
public Guid Id { get; set; }
public DateTime OrderDate { get; set; }

private List<Category> _categories;
public List<Category> Categories => _categories;
}
public class Category
{
public Guid Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }

public Guid OrderId { get; set; }
public Order Order { get; set; }

private List<RestrictionCategory> _restrictedCategories;
public List<RestrictionCategory> RestrictedCategories => _restrictedCategories;
}
public class RestrictionCategory
{
public Guid Id { get; set; }
public string Name { get; set; }
public Guid OrderId { get; set; }
public Order Order { get; set; }
public Guid CategoryId { get; set; }
public Category Category { get; set; }
public Guid RestrictedCategoryId { get; set; }
public Category RestrictedCategory { get; set; }
}
public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired();
}
}
public class CategoryConfiguration : IEntityTypeConfiguration<Category>
{
public void Configure(EntityTypeBuilder<Category> builder)
{
builder.HasKey(c => new { c.Id, c.OrderId });
builder.Property(o => o.Id).IsRequired();
builder.Property(o => o.OrderId).IsRequired();

builder.HasMany(c => c.RestrictedCategories).WithOne(cr => cr.Category)
.HasForeignKey(cr => new { cr.CategoryId, cr.OrderId
}).OnDelete(DeleteBehavior.NoAction);
}
}
public class RestrictionCategoryConfiguration : IEntityTypeConfiguration<RestrictionCategory>
{
public void Configure(EntityTypeBuilder<RestrictionCategory> builder)
{
builder.HasKey(c => new { c.Id, c.OrderId });
builder.Property(o => o.Id).IsRequired();
builder.Property(o => o.OrderId).IsRequired();

builder.HasIndex(cr => new { cr.RestrictedCategoryId, cr.OrderId });
}
}

`这些实体类似于实际实体。

最佳答案

实际上你得到了两个额外的列:

RestrictedCategoryId = table.Column<Guid>(nullable: false),
RestrictedCategoryId1 = table.Column<Guid>(nullable: true), // <--
RestrictedCategoryOrderId = table.Column<Guid>(nullable: true) // <--

显然是 EF Core Foreign Key Conventions不能很好地使用组合键,因此您必须显式配置关系 - 类似于您为其他关系所做的,只是因为您的模型没有相应的集合导航属性,您必须使用 HasMany具有泛型类型参数且没有参数,例如在 CategoryConfiguration 中:

builder.HasMany<RestrictionCategory>()
.WithOne(cr => cr.RestrictedCategory)
.HasForeignKey(cr => new { cr.RestrictedCategoryId, cr.OrderId})
.OnDelete(DeleteBehavior.NoAction);

关于sql-server - EF Core 添加迁移生成带有 ColumnName1 的额外列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60988981/

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