自联接实体对象更新为 NULL

本文关键字:更新 NULL 对象 实体 | 更新日期: 2023-09-27 17:55:47

我创建了一个具有自联接关系的实体框架。当我将自连接对象更新为某个值时,它已成功更新,但是当我想将此对象更新为 NULL 时。它抛出异常。这是我的代码:-

 var data = (from p in objContext.Categories where p.Id == model.Id select p).FirstOrDefault();
               if (model.Id != model.ParentId)
               {
                   data.Description = model.Description;
                   data.Name = model.Name;
                   data.LastChangeDate = DateTime.Now;
                   data.Slug = model.Slug;
                   data.Status = model.Status;
                   data.CreatedDates = DateTime.Now;
                   data.Id = model.Id;
                   if (model.ParentId == 0)
                   {
                      data.Category1 = null;
                   }
                   else
                   {
                       data.Category1 = (from p in objContext.Categories where p.Id == model.ParentId select p).SingleOrDefault();
                   }
                   objContext.SaveChanges();
                   return UserFriendlyMessage.CategoryUpdate;
               }
               else
               {
                   return UserFriendlyMessage.CategoryInvalidParent;
               }

以下是我的实体类:-

public partial class Category
    {
        public Category()
        {
            this.Posts = new HashSet<Post>();
            this.Categories = new HashSet<Category>();
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public System.DateTime CreatedDates { get; set; }
        public string Status { get; set; }
        public System.DateTime LastChangeDate { get; set; }
        public string Description { get; set; }
        public string Slug { get; set; }
        public virtual ICollection<Post> Posts { get; set; }
        public virtual ICollection<Category> Categories { get; set; }
        public virtual Category Category1 { get; set; }
    }

谢谢帕尔文·库马尔

自联接实体对象更新为 NULL

因此,

正如我从评论中了解到的那样,您要做的是将子类别保留在数据库中,但删除对其父类别的引用。

解决方案是设置子注释。父 ID 为空。

           if (model.Id != model.ParentId)
           {
               data.Description = model.Description;
               data.Name = model.Name;
               data.LastChangeDate = DateTime.Now;
               data.Slug = model.Slug;
               data.Status = model.Status;
               data.CreatedDates = DateTime.Now;
               data.Id = model.Id;
               if (model.ParentId == 0)
               {
                 **data.Category1.ParentId = null;**
               }
               else
               {
                   data.Category1 = (from p in objContext.Categories where p.Id == model.ParentId select p).SingleOrDefault();
               }
               objContext.SaveChanges();
               return UserFriendlyMessage.CategoryUpdate;
           }