【发布时间】:2021-07-18 08:06:56
【问题描述】:
添加没有父类的新类别时会发生此错误。我试过类似问题的答案,但没有结果。
型号
public class Category
{
[Column("CategoryId")]
public Guid Id { get; set; }
[Required(ErrorMessage = "Category name is a required field.")]
[MinLength(1, ErrorMessage = "Minimum length for the Name is 1 characters.")]
public string Name { get; set; }
[ForeignKey("ParentId")]
public Guid? ParentId { get; set; }
public virtual Category Parent { get; set; }
public virtual ICollection<Category> Children { get; set; }
}
请求
public class CategoryCreationDto
{
public Guid ParentId { get; set; }
public string Name { get; set; }
}
存储库
public void Create(T entity) => RepositoryContext.Set<T>().Add(entity);
public void CreateCategory(Category category) => Create(category);
控制器
Category categoryEntity = _mapper.Map<Category>(category);
_repository.Category.CreateCategory(categoryEntity);
await _repository.SaveAsync();
实体框架生成的表格
【问题讨论】:
-
顺便说一句,您的数据库设计不会阻止引用循环。
-
有问题吗?
-
无法测试,但在同一属性上将属性更改为
[ForeignKey("Parent")]或将属性按原样移动到 Parent 属性对我来说更有意义。 -
您显示的代码基本上是一个黑盒子。我们看不到
category/categoryEntity中的内容。 -
你在哪里为
CategoryId分配一个唯一值?
标签: c# entity-framework asp.net-core .net-core entity-framework-core