2016-12-24 87 views
1

型号代码:如何忽略EntityValidationErrors在服务器端

public partial class Content 
{ 
    public int ID { get; set; } 

    [Required(ErrorMessage = "Required.")] 
    public string ContentText1 { get; set; } 
} 

视图不包含相关内容的任何领域。在保存(控制器代码)

服务器端代码:

Content c = new Model.Content(); 
db.Contents.Add(c); 
db.Entry(pc).State = System.Data.Entity.EntityState.Added;     
db.SaveChanges(); 

这将导致一个错误:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

是否有可能避免这种错误,而不改变模型?

+0

继承类你为什么要这么做?为什么不只是删除所需的属性,如果你不想验证呢? – nemesv

+0

它已经在多个视图中使用。如果我删除验证,那么我需要在该视图中手动添加验证。 –

+0

如果你添加一个新的Content对象并且需要ContentText1,那么它必须被验证。当更新*时,想要跳过对某些属性的验证是更常见的情况。 –

回答

4

将这个声明在DB的构造,从DbContext

base.Configuration.ValidateOnSaveEnabled = false; 
+0

其工作正常。感谢@Hakam –

+0

@DevKumar很乐意为您效劳。请考虑接受这个答案,如果它适合你 –