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

検証エラーの原因となっているプロパティは会社と会社ですが、プロパティのコメントのみを更新したいです。

いくつかの助けをいただければ幸いです。

ありがとう

4

1 に答える 1

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

または、こちらで説明されているように、より洗練されたコードを記述できます。

于 2014-01-20T21:27:22.110 に答える