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 mem开发者_运维问答bers
//...
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.
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.
We've built a full-blown n-tier framework using L2S. We have a distinct UI layer, business logic layer and data access layer. Our entities are passed from the UI to the business layer for business process and validation, and then passed on to the DAL for the DB operations. The reverse is also true. A client makes a request for an entity which goes through the BLL, through to the DAL, and back to the client.
精彩评论