-1

This error occurs when adding new category with no parent. I have tried similar question's answers but no result.

Model

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; }

}

Request

public class CategoryCreationDto
{
    public Guid ParentId { get; set; }
    public string Name { get; set; }
}

Repository

public void Create(T entity) => RepositoryContext.Set<T>().Add(entity); 
public void CreateCategory(Category category) => Create(category);

Controller

 Category categoryEntity = _mapper.Map<Category>(category);
        _repository.Category.CreateCategory(categoryEntity);
        await _repository.SaveAsync();

Table generated by entity framework

Table generated by entity framework

Serge
  • 40,935
  • 4
  • 18
  • 45
MuhammedBalta
  • 472
  • 5
  • 14

2 Answers2

2

It's correlated with your entity relations.

Look at this example:

enter image description here

There is issue - when one entity can't exist with another. You can't have Order without Customer and Product.

You need to first INSERT record for *Customer and Product to add Product.


In your specific case:

First add those to db:

 public Guid? ParentId { get; set; }
    public virtual Category Parent { get; set; }
    public virtual ICollection<Category> Children { get; set; }

to add Category.


For optional foreign key:

modelBuilder.Entity<Category>()
    .HasOptional(p => p.Parent)
    .WithMany()
    .HasForeignKey(p => p.ParentId);
Piotr Żak
  • 2,046
  • 5
  • 18
  • 30
1

You will have to add fluent apis (repeat db migration after this)

 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
  modelBuilder.Entity<Category>()
            .HasOne(s => s.Parent)
            .WithMany(m => m.Children)
            .HasForeignKey(e => e.ParentId);

 OnModelCreatingPartial(modelBuilder);
 }

I am sorry but since you didn't post what is your mapper doing and what is inside of category, I will post the whole code for the test (it was tested in VS)

        var categoryEntity = new Category {Id=new Guid(), Name="CategoryName"};
        context.Set<Category>().Add(categoryEntity ); 
        await context.SaveChangesAsync();
Serge
  • 40,935
  • 4
  • 18
  • 45