locked
Odata WCF Data service turn on validation RRS feed

  • Question

  • I am not getting validation from ef when MaxLength of a property is exceeded.  This is made worse because SQL Server has a weak error when the length is exceeded - it doesn't say which column is in error!

    It looks like there is a configuration property ValidateOnSaveEnabled which I can set to turn on validation;however I don't see where I can turn this on in the wcf data service.  


    Tuesday, August 23, 2011 2:40 PM

Answers

  • The DbContext.Configuration property is where you set ValidateOnSaveEnabled; this is an Entity Framework 4.1 behavior (you can download EF 4.1 from NuGet.org).

    You can use EF 4.1 and all the Code First goodies with WCF Data Services, but it's a little trickier because the data service is expecting to get a strongly-typed ObjectContext rather than a strongly-typed DbContext. My blog post Entity Framework 4.1: Code First and WCF Data Services shows how to use a DbContext as the data provider for WCF Data Services.

    In my post, you notice that you have to override the CreateDataSource method in the data service to manually supply an ObjectContext, which is derived from the DbContext. This gives you a chance to configure the DbContext:

    protected override ObjectContext CreateDataSource()
    {
     NorthwindContext nw = new NorthwindContext();
     
     // Configure DbContext before we provide it to the 
     // data services runtime.
     nw.Configuration.ValidateOnSaveEnabled = true;
       
     // Get the underlying ObjectContext for the DbContext.
     var context = ((IObjectContextAdapter)nw).ObjectContext; 
     context.ContextOptions.ProxyCreationEnabled = false;
        
     // Return the underlying context.
     return context;
    }
    
    

    To be honest, I haven't messed around much with validation in EF 4.1. It seems like validation is on by default, so setting ValidateOnSaveEnabled = true may not even be needed.

    Cheers,

    Glenn Gailey


    Please visit my blog

    This posting is provided "AS IS" with no warranties, and confers no rights.
    • Marked as answer by PapaStoke Friday, August 26, 2011 1:06 PM
    Wednesday, August 24, 2011 7:54 AM