cll*_*pse 13 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 = "";
}
}
Run Code Online (Sandbox Code Playgroud)
使用已实现的业务逻辑:
// 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: ""
Run Code Online (Sandbox Code Playgroud)
此外:LINQ to SQL 实体类本质上是非常开放的。这意味着与dbo.Products.ProductId列对应的属性同时实现 getter 和 setter — 该字段不应更改。
据我所知,您无法使用分部类覆盖属性,因此我通常做的是实现一个管理器,该管理器使用接口缩小对象范围:
public interface IProduct
{
Int32 ProductId { get; }
void Delete();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9405 次 |
| 最近记录: |