2008-10-21 22 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。