C# 重命名在fluent api中不起作用的外键列
我正在尝试制作一个自参考表C# 重命名在fluent api中不起作用的外键列,c#,entity-framework,ef-fluent-api,C#,Entity Framework,Ef Fluent Api,我正在尝试制作一个自参考表 public class Category { // PK public int CategoryId { get; set; } // Property public string CategoryName { get; set; } // FK public int? ParentCategoryId { get; set; } public virtual ICollection<Categor
public class Category
{
// PK
public int CategoryId { get; set; }
// Property
public string CategoryName { get; set; }
// FK
public int? ParentCategoryId { get; set; }
public virtual ICollection<Category> ParentCategories { get; set; }
public virtual ICollection<Product> Products { get; set; } // Product is defined later
}
以及产品
配置
public class ProductConfiguration:EntityTypeConfiguration<Product>
{
public ProductConfiguration():base()
{
// Many-to-Many
HasMany(c => c.Categories)
.WithMany()
.Map(p =>
{
p.MapLeftKey("ProductRefId");
p.MapRightKey("CategoryRefId");
p.ToTable("ProductCategory");
});
}
}
外键按预期变成了
ParentCategoryId
。问题解决了,我犯了一个错误。我没有将配置挂接到DbContext
通过将这些列添加到DbContext
,可以按预期重命名这些列
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new CategoryConfiguration());
modelBuilder.Configurations.Add(new ProductConfiguration());
}
首先,不要调用empty base(),它将在类中运行ctor之前由调用。其次,删除这个HasKey(c=>new{c.CategoryId});只写HasKey(c=>c.CategoryId);关于你的问题,db中列的名称是什么?嗨,@Chase。谢谢你的建议。外键列名是
Category\u CategoryId
,我想使用ParentCategoryId
作为其名称。
public class ProductConfiguration:EntityTypeConfiguration<Product>
{
public ProductConfiguration():base()
{
// Many-to-Many
HasMany(c => c.Categories)
.WithMany()
.Map(p =>
{
p.MapLeftKey("ProductRefId");
p.MapRightKey("CategoryRefId");
p.ToTable("ProductCategory");
});
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>()
.HasOptional(c => c.ParentCategories)
.WithMany()
.HasForeignKey(c => c.ParentCategoryId);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new CategoryConfiguration());
modelBuilder.Configurations.Add(new ProductConfiguration());
}