Search code examples
linqpresentationlayersubmitchangesinsertonsubmit

In which layer to make linq-sql calls as SubmitChanges(), InsertOnSubmit() etc


Which layer is the best layer to make linq-sql calls as SubmitChanges(), InsertOnSubmit() etc.

For example, let's say I have two tables Parent and Child. Child table has foreign key on parent (Child table has ParentId column). I want to insert parent object and child objects into the db.

Using linq-sql, I can do this.

Parent parent = new Parent();
Child child1 = new Child();
Child child2 = new Child();
//assign values to parent data members
//...

parent.Childs.Add(child1);
parent.Childs.Add(child2);

using (DataContext db = new DataContext())
{
   db.Parents.InsertOnSubmit(parent);
   db.SubmitOnChanges();  
}

Am I mixing Presentation layer code with data access layer? If so, how do I do it with a business layer object in between?

Please let me know. Thanks.


Solution

  • Having the data access right there within the presentation layer is probably not the best way to do it.

    You could implement a Writer class which has methods that access the DataContext.

    Parent parent = new Parent();
    Child child1 = new Child();
    Child child2 = new Child();
    //assign values to parent data members
    //...
    
    parent.Childs.Add(child1);
    parent.Childs.Add(child2);    
    
    using (var parentWriter = new ParentWriter())
    {
      parentWriter.Insert(parent)
    }
    

    Then in the wrapper class

    public class ParentWriter : IDisposable
    {
      private DataContext _dc;
    
      public ParentWriter()
      {
        _dc = new DataContext();
      }
    
      public void Insert(Parent parent)
      {
        _dc.Parents.InsertOnSubmit(parent);
        _dc.SubmitOnChanges();
      }
    
      //IDisposable Members
      //...
    }
    

    This is quite a simplified example and is untested. I have used a similar design in a recent project where we have specific Writer and Reader classes that split the data access depending on what we're doing with the data.