我正在尝试制作一个自引用表
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 CategoryConfiguration : EntityTypeConfiguration<Category>
{
public CategoryConfiguration():base()
{
HasKey(c => new { c.CategoryId });
HasOptional(c => c.ParentCategories)
.WithMany()
.HasForeignKey(c => c.ParentCategoryId );
}
}
这个想法是使用ParentCategoryId
作为列名,但它不起作用。相反,它生成了一个名为Category_CategoryId
的列。
我尝试使用.Map(c => c.MapKey("ParentCategoryId"))
,结果是一样的。
我不认为这是自我引用的原因,因为同样的事情发生在多对多的关系中:
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
和Product
配置
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");
});
}
}
表格名称为ProductCategories
而不是ProductCategory
外键是Product_ProductId
和Category_CategoryId
他们都不是所期待的。
我该如何解决这个问题?请帮忙。
谢谢!
<小时/> 更新1
奇怪的是,如果我通过DbModelBuilder
定义它,那么它可以正常工作
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>()
.HasOptional(c => c.ParentCategories)
.WithMany()
.HasForeignKey(c => c.ParentCategoryId);
}
外键变为ParentCategoryId
为预期。
答案 0 :(得分:0)
问题解决了,我犯了一个错误。我没有将配置挂钩到DbContext。
将这些列添加到DbContext
中,列将按预期重命名。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new CategoryConfiguration());
modelBuilder.Configurations.Add(new ProductConfiguration());
}