使用虚拟属性更新类时,实体框架验证失败

时间:2012-06-29 14:53:01

标签: entity-framework entity-framework-4.1 entity-framework-4.3

当类包含虚拟属性时,我在更新类的属性时遇到问题。这是我的代码

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

导致验证错误的属性是公司和公司,但我只想更新属性注释。

一些帮助表示赞赏。

由于

1 个答案:

答案 0 :(得分:1)

当您尝试保存实体时,EF不会延迟加载您的虚拟属性(该死的)。 您可以执行以下任一操作。

使用包含:

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

或使用加载:

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();

或者更好的是,您可以按照here所述编写更优雅的代码。