Self referencing entity CRUD EF CORE

.net c# crud entity-framework-core

Question

I have trouble to do a CRUD for self reference entity.

This is my entity:

public class Category
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public virtual ICollection<Recipe> Recipes { get; set; } = new HashSet<Recipe>();
    public int? ParentId { get; set; }
    public virtual Category Parent { get;set; }
    public virtual ICollection<Category> Categories { get; set; } = new HashSet<Category>();
}

ModelBuilder:

modelBuilder.Entity<Category>()
    .WithMany(c => c.Categories)
    .HasOne(c => c.Parent)
    .HasForeignKey(c => c.ParentId);

My create logic:

public void Save(Category category)
{
    if(category.Parent != null && category.Parent.Id == 0)
    {
       category.Parent = null;
    }
    else
    {
        _db.Entry(category.Parent).State = EntityState.Unchanged;
    }
    _db.Category.Add(category);
    _db.SaveChanges();
}

Update logic:

public void Update(Category category)
{
    _db.Category.Update(category);
    _db.SaveChanges();
}

CategoryDto class:

public class CategoryDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public CategoryDto Parent { get; set; }
}

I am not able to save this object to database, because seems like Parent wants to be saved as well, getting that Name field is required.

Any ideas how CRUD should look like for a self referencing entity?

Any answers are appreciated.

1
0
7/29/2018 11:53:52 AM

Popular Answer

You have to configure the serializer to ignore circular references in your project.

So for this you have to add following line of code inside ConfigureServices method in Startup.cs

Like

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
    .AddJsonOptions(options => {
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });
}

After adding this line of codes you will be able to insert records in table with have circular reference.

1
7/28/2018 7:36:32 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow