2008-10-21 23 views

回答

3

我发现了一种我认为最好的模式 - 至少在我的情况下。


我延伸使用部分类实体类。我使用部分类,因此实体的签名不会更改(请参阅Delete方法中的DeleteOnSubmit调用)。

我已经制作了一个小例子。这里的数据库和LINQ to SQL类设置的图像:



而这里的中,我实现业务逻辑部分类:

/// <summary> 
/// This class extends BusinessLogicDataContext.Products entity class 
/// </summary> 
public partial class Product 
{ 
    /// <summary> 
    /// New up a product by column: dbo.Products.ProductId in database 
    /// </summary> 
    public Product(Int32 id) 
    { 
     var dc = new BusinessLogicDataContext(); 

     // query database for the product 
     var query = (
      from p in dc.Products 
      where p.ProductId == id 
      select p 
     ).FirstOrDefault(); 

     // if database-entry does not exist in database, exit 
     if (query == null) return; 

     /* if product exists, populate self (this._ProductId and 
      this._ProductName are both auto-generated private 
      variables of the entity class which corresponds to the 
      auto-generated public properties: ProductId and ProductName) */ 
     this._ProductId = query.ProductId; 
     this._ProductName = query.ProductName; 
    } 


    /// <summary> 
    /// Delete product 
    /// </summary> 
    public void Delete() 
    { 
     // if self is not poulated, exit 
     if (this._ProductId == 0) return; 

     var dc = new BusinessLogicDataContext(); 

     // delete entry in database 
     dc.Products.DeleteOnSubmit(this); 
     dc.SubmitChanges(); 

     // reset self (you could implement IDisposable here) 
     this._ProductId = 0; 
     this._ProductName = ""; 
    } 
} 

使用实现的业务逻辑:

// new up a product 
var p = new Product(1); // p.ProductId: 1, p.ProductName: "A car" 

// delete the product 
p.Delete(); // p.ProductId: 0, p.ProductName: "" 

此外:LINQ to SQL实体类本质上是非常开放的。这意味着对应于dbo.Products.ProductId列的属性实现了一个getter和setter - 该字段不应该是可更改的。

要我使用性质部分类,所以我通常做的是实现使用一个接口,它缩小了对象管理器不能覆盖的知识:

public interface IProduct 
{ 
    Int32 ProductId { get; } 

    void Delete(); 
} 
1

现在我试图使用LINQ到SQL实体类为业务对象,要通过他们周围的功能和服务之间。

当然,您应该有单独的实体类用于数据库访问,因此您的数据库布局可以更改而无需更改业务对象!

我也会对这个很好的解决方案感兴趣!

0

我没有使用实体框架和LINQ到实体,以此来进一步从数据库中分离出来我的客户端代码进行一些实验,但我发现它笨拙的使用,并担心性能。

在我目前的项目中,我使用的LINQ to SQL作为我的数据层,但有在这里我实现所有的LINQ查询单独的类。这些类返回在我的Linq到SQL上下文中定义的实体,但查询隐藏在方法中。

2

我倾向于使用Repository模式来封装DataContexts。

Repository Pattern

我想找到一个更好的方法,而使用LINQ2SQL虽然从我的数据层发出POCO对象。

0

我发现Ian Cooper on CodeBetter.comStephen Walther系列的文章对理解首先编写POCO实体的需求非常有用,然后将它们映射到数据库,而不是以相反的方式进行(这是我以前常用的做法)。

0

我玩弄的想法有OO模型(对面向对象的做法更好的支持)的单独的层,但是使用LINQ到引擎盖下的SQL。这个想法是有一个自定义工具将用来生成代码的xml文件。 由于LINQ to SQL实体对于我的首选项来说太混乱了,我会自动生成新的类作为我的实体使用,当然DataContext对于客户端代码也是完全隐藏的。 简短的回答是:创建新的实体类,但使用底层的LINQ to SQL实体和DataContext。