linq-to-sql - LINQ to SQL 实体和数据上下文类 : business object encapsulation

标签 linq-to-sql c#-3.0

您最喜欢将 LINQ to SQL 实体类和数据上下文类封装到业务对象中的方法是什么?

你发现什么在特定情况下有效?

你有没有发明或采用任何特定的模式?

最佳答案

我找到了一种我认为效果最好的模式——至少就我而言。

我使用部分类扩展实体类。我使用部分类,因此实体的签名不会改变(参见 DeleteOnSubmit 方法中的 Delete 调用)。

我做了一个小例子。这是数据库和 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——这个字段不应该是可更改的。

据我所知,你不能使用部分类覆盖属性,所以我通常做的是实现一个使用接口(interface)缩小对象的管理器:
public interface IProduct
{
    Int32 ProductId { get; }

    void Delete();
}

关于linq-to-sql - LINQ to SQL 实体和数据上下文类 : business object encapsulation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/223931/

相关文章:

linq - 如何对 Linq to SQL 自动生成的部分扩展进行编码?

.net - 为什么我会收到 "method has no supported translation to SQL"错误?

c# - Linq to SQL 的问题

wpf - 将快捷键分配给 WPF 中的按钮

c# - 如何在 Xamarin.forms 的轮播页面中以编程方式更改页面?

linq - 等同于 JOIN 的点符号

sql - 嵌套查询没有合适的键

winforms - Winforms 中使用 linq-to-sql 进行 CRUD

sql-server - NHibernate 标识符更改异常

c# - 为什么 C# 3 允许将文字零 (0) 隐式转换为任何枚举?