У меня есть класс Category, который может иметь несколько подкатегорий и только одну. родитель. Я уже проводил подобные занятия, но впервые использую отношение «один ко многим» и самоссылку, и у меня возникли проблемы при добавлении категории.
Вот мой код:
- Category.cs:
Код: Выделить всё
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 SubCategories { get; set; }
}
- ShopDbContext.cs:
Код: Выделить всё
public class ShopDbContext : DbContext
{
public DbSet Category { get; set; }
public ShopDbContext(DbContextOptions options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity()
.HasOne(c => c.ParentCategory)
.WithMany(c => c.SubCategories)
.HasForeignKey(c => c.ParentCategoryId);
}
}
- CategoryRepository.cs:
Код: Выделить всё
public class CategoryRepository : ICategoryRepository
{
private readonly ShopDbContext _dbContext;
public CategoryRepository(ShopDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task AddCategoryAsync(Category category)
{
_dbContext.Category.Add(category);
await _dbContext.SaveChangesAsync();
return category;
}
}
- CategoryController.cs:
Код: Выделить всё
[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 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"
}
Код: Выделить всё
{
"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"
}
Я что-то напутал? с моей конфигурацией? Мои аннотации? Я провел много исследований, и мои отношения «один ко многим» кажутся мне хорошими.
Спасибо за помощь
Подробнее здесь: https://stackoverflow.com/questions/758 ... -self-refe