Tôi đã tìm thấy một mô hình mà tôi nghĩ rằng hoạt động tốt nhất - Trong trường hợp của tôi, ít nhất.
Tôi mở rộng các lớp thực thể sử dụng các lớp một phần. Tôi sử dụng các lớp học một phần để chữ ký của thực thể không thay đổi (xem các cuộc gọi DeleteOnSubmit
trong phương thức Delete
).
Tôi đã nấu một ví dụ nhỏ.Dưới đây là một hình ảnh của cơ sở dữ liệu và LINQ to setup lớp SQL:
Và đây là partial class trong đó tôi thực hiện logic kinh doanh:
/// <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 = "";
}
}
Sử dụng logic kinh doanh thực hiện:
// 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: ""
Hơn nữa: các lớp thực thể LINQ to SQL rất cởi mở trong tự nhiên. Điều này có nghĩa là thuộc tính tương ứng với cột dbo.Products.ProductId thực hiện cả trình khởi động và trình đổi - trường này không thể thay đổi được.
Theo hiểu biết của tôi bạn không thể ghi đè các thuộc tính sử dụng các lớp học phần, vì vậy những gì tôi thường làm là thực hiện một người quản lý mà thu hẹp đối tượng sử dụng một giao diện:
public interface IProduct
{
Int32 ProductId { get; }
void Delete();
}
Đặt thành cộng đồng wiki. – roosteronacid