您最喜欢将 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/