Question

Whenever I want to remove hierarchy of objects meaning a Menu object containing another Menu object in it. But it works fine if single object is removed (without any object inside). I am getting the following error:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

This is what my type looks like:

 public class Menu
    {
        public string Reference { get; set; }

        [JsonProperty("text")]
        [MaxLength(30), MinLength(2)]
        public string DisplayText { get; set; }

        [MaxLength(150)]
        public string HyperLink { get; set; }

        private List<Menu> menus;
        [JsonProperty("items")]
        public virtual List<Menu> Menus
        {
            get 
            {
                if (menus == null || menus.Count == 0)
                {
                    return null;
                }

                return menus;
            }
            set { menus = value; }
        }
    }

Configuration:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
       modelBuilder.Entity<Menu>().HasKey(k => k.Reference);
   }

Following is how I am removing:

List<Menu> menu = JsonConvert.DeserializeObject<List<TMenu>>(Menu);

            using (DataContext context = new DataContext())
            {
                if (context.Menus.Count() != 0)
                {
                    foreach (var item in menu)
                    {
                        Menu deleteMenu = context.Menus.Where(f => f.Reference == item.Reference).FirstOrDefault();
                        context.Menus.Remove(deleteMenu);
                    }

                    context.SaveChanges();
                }
            }

I would really appreciate a suggestion on this.

Was it helpful?

Solution

Long story short, SQL Server cannot do recursive delete even though PostGres can I read. Anyway, I had to create a trigger on the table where recursive delete was manually made.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top