自联接实体对象更新为NULL

时间:2015-06-12 09:58:14

标签: c# linq entity-framework

我创建了一个具有自我加入关系的实体框架。当我将自己加入的对象更新为某些值时,它会成功更新,但是当我想将此对象更新为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; }
    }

谢谢, Parveen Kumar

1 个答案:

答案 0 :(得分:0)

据我所知,
您要做的是将子类别保留在数据库中,但删除对其父类别的引用。

对此的解决方案是将subcomment.ParentId设置为null。

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