Model 以 Linq to SQL Shop.dbml 為基礎,透過 partial class 於 Model 資料夾擴充領域邏輯。以 Product 為例:
private int _ProductId; private int _CategoryId; private string _Name;
private string _Description; private decimal _Price; private int _Position;
private int _Weight; private bool _IsActive; private string _UrlName;
public partial class Product : IOrderable, IActivatable, IUrlNamed {
partial void OnNameChanging(string value) { value.Label("Name").IsRequired(); }
partial void OnNameChanged() { UrlName = Name.ToUrlFriendly(); }
partial void OnDescriptionChanging(string value) { value.Label("Description").IsRequired(); }
public bool HasMainImage { get { return this.ProductImages.Count > 0; } }
public Image MainImage { get { return HasMainImage ? this.ProductImages.InOrder().First().Image : null; } }
public bool HasSize { get { return this.Sizes.Active().Count() > 0; } }
public Size DefaultSize { get { if (this.Sizes.Count() == 0) throw new ApplicationException("Product has no default size"); return this.Sizes[0]; } }
public string IsActiveAsString { get { return IsActive ? string.Empty : " Not Active"; } }
public static Product DefaultProduct(int parentCategory, int position) {
return new Product { ProductId = 0, CategoryId = parentCategory, Position = position };
}
}
展示了 partial method 驗證、導航屬性封裝、介面實作與工廠方法等領域模型豐富技巧。