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

[在實體框架中修改實體上的屬性導致驗證錯誤]的可能重複(http://stackoverflow.com/questions/8784005/modifying-a-property-on-an-entity-in-entity-framework -causes驗證錯誤) – Eranga

回答

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你可以寫出更優雅的代碼。

相關問題