0

哪一层是进行 linq-sql 调用的最佳层,如 SubmitChanges()、InsertOnSubmit() 等。

例如,假设我有两个表 Parent 和 Child。子表在父表上有外键(子表有 ParentId 列)。我想将父对象和子对象插入数据库。

使用 linq-sql,我可以做到这一点。

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();  
}

我是否将表示层代码与数据访问层混合在一起?如果是这样,我该如何处理中间的业务层对象?

请告诉我。谢谢。

4

2 回答 2

1

在表示层中直接访问数据可能不是最好的方法。

您可以实现一个 Writer 类,该类具有访问 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)
}

然后在包装类中

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
  //...
}

这是一个非常简化的示例,未经测试。我在最近的一个项目中使用了类似的设计,其中我们有特定的 Writer 和 Reader 类,它们根据我们对数据的处理方式来拆分数据访问。

于 2010-02-08T23:42:57.500 回答
0

我们已经使用 L2S 构建了一个成熟的 n 层框架。我们有一个独特的 UI 层、业务逻辑层和数据访问层。我们的实体从 UI 传递到业务层进行业务流程和验证,然后传递到 DAL 进行数据库操作。反之亦然。客户端向通过 BLL、DAL 并返回客户端的实体发出请求。

于 2010-02-08T23:36:04.753 回答