Entity Framework validation failed when updating a class with virtual properties

别等时光非礼了梦想. 提交于 2019-12-12 16:04:34

问题


I'm having problems updating a property of a class when the class contains virtual properties. Here is my code

 public class Policy
            {
                [Key]
                [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
                public long id { get; set; }

                [UIHint("Company"), Required]
                public virtual Company company { get; set; }

                [UIHint("Productor"), Required]
                public virtual Productor productor { get; set; }

                [MaxLength(1000)]
                public string comments { get; set; }
            }

        public class Company
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public long id { get; set; }

            [MaxLength(100)]
            public string name { get; set; }

        }

    //Then Productor class is the same as company but with another name

     public static int updateComment(long id, string comments)
            {
                MemberPolicies mp = new MemberPolicies();

                Policy p = mp.Policies.Single(o => o.id == id);
                p.comments = comments;

                int afectedRecords = -1;
                try
                {
                    afectedRecords = mp.SaveChanges();
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }
                }
                return afectedRecords;
            }

The properties which are causing the validation errors are company and company, but I only want to update the property comment.

Some help is appreciate.

Thanks


回答1:


EF does not lazy load your virtual properties when you try to save your entity (damn it). You can do either of the following.

Use Include:

Policy p = mp.Policies
    .Include(p => p.company)
    .Include(p => p.productor).Single(o => o.id == id);
p.comments = comments;

Or use Load:

Policy p = mp.Policies.Single(o => o.id == id);
p.comments = comments;
mp.Entry(p).Reference(p => p.company).Load();
mp.Entry(p).Reference(p => p.productor).Load();

Or better you can write more elegant code as explained here.



来源:https://stackoverflow.com/questions/11264046/entity-framework-validation-failed-when-updating-a-class-with-virtual-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!