我正在尝试使用 Entity Code-First 创建一个 API 来操作 MySQL 数据库中的数据。
我有一个类别类,它可以有多个子类别,并且只有一个父类别。我已经做过类似的课程,但这是我第一次使用一对多关系和自引用,而且我在添加类别时遇到了麻烦。
这是我的代码:
public class Category
{
[Key]
[Column("id")]
public int Id { get; set; }
[Column("parent_category_id")]
public int? ParentCategoryId { get; set; }
[Column("name")]
public String Name { get; set; }
[Column("description")]
public string Description { get; set; }
[ForeignKey("ParentCategoryId")]
public virtual Category ParentCategory { get; set; }
[ForeignKey("Id")]
public virtual ICollection<Category> SubCategories { get; set; }
}
public class ShopDbContext : DbContext
{
public DbSet<Category> Category { get; set; }
public ShopDbContext(DbContextOptions<ShopDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Category>()
.HasOne(c => c.ParentCategory)
.WithMany(c => c.SubCategories)
.HasForeignKey(c => c.ParentCategoryId);
}
}
public class CategoryRepository : ICategoryRepository
{
private readonly ShopDbContext _dbContext;
public CategoryRepository(ShopDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<Category> AddCategoryAsync(Category category)
{
_dbContext.Category.Add(category);
await _dbContext.SaveChangesAsync();
return category;
}
}
[Route("api/v1/[controller]")]
[ApiController]
public class CategoryController : Controller
{
private readonly ICategoryRepository _categoryRepository;
public CategoryController(ICategoryRepository categoryRepository)
{
_categoryRepository = categoryRepository;
}
// POST: api/v1/Category
[HttpPost]
public async Task<IActionResult> AddCategory([FromBody] Category category)
{
await _categoryRepository.AddCategoryAsync(category);
return CreatedAtAction("GetCategoryById", new { id = category.Id }, category);
}
}
我的目标是添加以下类别:
{
"parentCategoryId": 0,
"name": "First Category",
"description": "The first category, without parent"
}
当我尝试我的 AddCategory 函数时,出现以下错误:
{
"errors": {
"SubCategories": [
"The SubCategories field is required."
],
"ParentCategory": [
"The ParentCategory field is required."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "0HMPA9OFPSJK8:0000000F"
}
不需要这些字段,因为外键应该用我数据库中的相应数据填充这些对象。
我搞砸了我的配置吗?我的注释?我做了很多研究,我的“一对多”关系对我来说似乎很好
感谢您的帮助