none
Validation in Linq RRS feed

  • Question

  • Hi,
       It is my first time using LINQ to sql. I had a quick question on validation. I would like to make certain columns 'required' by adding an attribute to the partial class. I am not using a dynamic site, but I tried using the metadata attribute and it did not work.

    Any advise is appreciated.

    Thanks
    • Edited by N.Afache Thursday, July 9, 2009 8:15 PM
    Thursday, July 9, 2009 8:14 PM

All replies

  • You may want to take a look at the partial function OnValidate that exist on all L2S-generated entity classes. Implement it with your validation logic, and L2S will call it when objects need to be validated (b4 hitting the database).
    Kristofer - Huagati Systems Co., Ltd. - Cool tools for Linq-to-SQL and Entity Framework: www.huagati.com/dbmltools (VS designer add-in), www.huagati.com/L2SProfiler (query profiler for L2S)
    Friday, July 10, 2009 3:56 AM
    Answerer
  • Hi,
       Yes true I can use the onValidate Event. That is server side error handling though. Is there a way I could throw the exception and have it caught by the validator in my UI with out using Dynamic data websites? What is the best way to handle exceptions thrown from the partial function?

    Thanks
    Friday, July 10, 2009 6:06 AM
  • If you're using normal asp.net webforms without any dynamic stuff generating forms etc, I'd recommend using the normal asp.net validation controls. Sure, it will lead to duplicated validation logic but will save you the trouble of a roundtrip.
    Kristofer - Huagati Systems Co., Ltd. - Cool tools for Linq-to-SQL and Entity Framework: www.huagati.com/dbmltools (VS designer add-in), www.huagati.com/L2SProfiler (query profiler for L2S)
    Friday, July 10, 2009 6:34 AM
    Answerer
  • Okay lets say I did not use the validation controls in my web form, and I used the Onvalidate or onColumnChanging partial functions. When an exception gets thrown from the partial class how would I handle it in my UI. Do you have an example on how to handle those exceptions in UI?

    Thanks

    Friday, July 10, 2009 6:50 AM
  • Depending a little bit on how your app is layered etc you could do somehting like this. This is from a webforms app where L2S DataContext is part of the web app itself. The normal asp.net validation controls (requiredfieldvalidator, regularexpresisonvalidator etc) are in place in the forms to catch any errors before even hitting the datacontext, but should that fail there's some business logic validation in the datacontext itself.

    partial class Broker
    {
        partial void OnValidate(ChangeAction action)
        {
            if (action == ChangeAction.Update)
            {
                if (string.IsNullOrEmpty(this.CurrencyCode))
                {
                    throw new BrokerValidationErrorException("Missing default currency code.");
                }
            }
    ...
    
        }
    
        public bool SaveBroker()
        {
            using (HedgehogDataContext dc = HedgehogDataContext.GetHedgehogDC())
            {
                if (this.ID == Guid.Empty)
                {
                    dc.Brokers.InsertOnSubmit(this);
                }
                else
                {
                    dc.Brokers.Attach(this, true);
                }
                dc.SubmitChanges();
                return true;
            }
        }
    
    ...
    
        public class BrokerValidationErrorException : Exception
        {
            public BrokerValidationErrorException(string message)
                : base(message)
            { }
        }
    }
    ...and then in the webform itself:

    bool success = false;
    try
    {
        success = currentBroker.SaveBroker();
    }
    catch (Broker.BrokerValidationErrorException be)
    {
        ScriptManager.RegisterStartupScript(this, this.GetType(), "BrokerValidationErrorAlert", "alert('" + be.Message + "');", true);
    }
    
    if (success)
    {
        //close the window
        string closeWndScript = "window.opener.LoadBrokers();\r\nwindow.close();";
        ScriptManager.RegisterStartupScript(Page, this.GetType(), "CloseWndScript", closeWndScript, true);
    }

    Kristofer - Huagati Systems Co., Ltd. - Cool tools for Linq-to-SQL and Entity Framework: www.huagati.com/dbmltools (VS designer add-in), www.huagati.com/L2SProfiler (query profiler for L2S)
    Friday, July 10, 2009 7:24 AM
    Answerer
  • I got the idea thanks. I guess I would do as much validations as i can on the client side, and I would use the data context business logic for stuff that cannot be validated on the client. Does that sound reasonable? I hope it is not off topic, but do you have any links for some enlightment about how my application should be layered? 
    Friday, July 10, 2009 7:40 AM
  • I got the idea thanks. I guess I would do as much validations as i can on the client side, and I would use the data context business logic for stuff that cannot be validated on the client. Does that sound reasonable? I hope it is not off topic, but do you have any links for some enlightment about how my application should be layered? 

    Yup, that is a good idea.

    As for layering the application - it depends completely on what kind of application and if/how much code reuse you expect to have in the future. For specialized web apps with no scalability concerns and little code-reuse in other apps etc, a single layer (web app with built in DC etc) is often sufficient. If on the other hand your DAL and/or business logic will be reused from other apps the other extreme is DC and all queries in a separate class library, then a WCF layer with server-side business logic on top of that, a client side business logic layer (for client side business logic and wrapping the service references) in a class library, and finally the web app or winforms app referencing the client-side business logic layer. More layers means easier code-reuse and swapping-out of portions in the future, but of course means more initial work to build the layers and ensure that every piece of code goes in the right layer...
    Kristofer - Huagati Systems Co., Ltd. - Cool tools for Linq-to-SQL and Entity Framework: www.huagati.com/dbmltools (VS designer add-in), www.huagati.com/L2SProfiler (query profiler for L2S)
    Friday, July 10, 2009 8:05 AM
    Answerer
  • Hi Krisofer,
      When I call a stored procedure using linq, or call a custom sql command using Linq, Do the 'onvalidate' and 'oncolumnChanging' events get fired?
    What is more efficient to use LINQ queries or Stored procedures?





     

     

     

     

     

    Friday, July 10, 2009 2:36 PM