我有一个数据库关系,如下所示。域对象是基于 LINQ to SQL ORM 创建的。
付款包括现金付款和礼券付款。假设购买总金额为550,可按以下方式支付
1 Gift Coupon Valued 300
1 Gift Coupon Valued 200
I Cash Currency Valued 50
我正在使用 ORM 的“InsertOnSubmit”功能插入新的付款记录。以下代码工作正常。但是,如果公司使用信用卡引入新的支付组件,我需要更改我的“支付”域类。我如何使付款类 为扩展打开并因更改而关闭 仍然使用 ORM ?
注意:支付类具有 行为 (例如 GetTotalAmountCollected)。我正在尝试制作“付款”类(class)以满足 OCP。
注意:优惠券类型有一个特定的 行为 。如果 Coupon 发行日期小于 1/1/2000,则不应用于计算 Total Amount(即 CouponValue 应为零)。另请参阅 Refactoring code using Strategy Pattern。
注意:我使用的是 .Net 4.0
引用:
http://weblogs.asp.net/manavi/archive/2010/12/28/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt.aspx
C# 代码:
public class PaymentAppService
{
public RepositoryLayer.ILijosPaymentRepository Repository { get; set; }
public void MakePayment()
{
DBML_Project.Payment paymentEntity = new DBML_Project.Payment();
paymentEntity.PaymentID = 1;
paymentEntity.PaymentType = "PurchaseP";
DBML_Project.CashPayment cashObj = new DBML_Project.CashPayment();
cashObj.CashPaymentID = 1;
cashObj.CurrencyNumber = 123;
cashObj.CurrencyValue = 100;
DBML_Project.GiftCouponPayment giftCouponObj = new DBML_Project.GiftCouponPayment();
giftCouponObj.GiftCouponPaymentID = 1;
giftCouponObj.CouponValue = 200;
giftCouponObj.CouponNumber = 124;
paymentEntity.CashPayments = new System.Data.Linq.EntitySet<DBML_Project.CashPayment>();
paymentEntity.CashPayments.Add(cashObj);
paymentEntity.GiftCouponPayments = new System.Data.Linq.EntitySet<DBML_Project.GiftCouponPayment>();
paymentEntity.GiftCouponPayments.Add(giftCouponObj);
Repository.InsertEntity(paymentEntity);
Repository.SubmitChanges();
}
}
存储库:
public class LijosPaymentRepository : ILijosPaymentRepository
{
public System.Data.Linq.DataContext MyDataContext { get; set; }
public void InsertEntity(DBML_Project.Payment payment)
{
//Insert the entity
MyDataContext.GetTable<DBML_Project.Payment>().InsertOnSubmit(payment);
}
public void SubmitChanges()
{
MyDataContext.SubmitChanges();
}
}
最佳答案
对于@Lijo 试图解决抽象方法的问题会更好
我认为您可以在 CashPayment 类型上创建一个实现您自己的 IPayment 接口(interface)的部分类,该类可以在整个应用程序中使用。这个接口(interface)也可以在 CreditCardPayment 上:
例子:
public interface IPayment
{
int Id { get; set; }
int PaymentId { get; set; }
//Other payment specific properties or methods
}
public partial class CashPayment : IPayment
{
public int Id
{
get { return CashPaymentId ; }
set { CashPaymentId = value; }
}
//Other properties
}
public partial class CreditCardPayment : IPayment
{
//more code ...
}
在您的 EF 上下文中获取所有付款的内容
public partial class PaymentEntities //The name of your EF entities
{
public IQueryable AllPayments
{
return this.CashPayment.Union(this.CreditCardPayment); //This is not good, but just an example. The abstract class approach would be better here.
}
public void InsertPayment(IPayment payment)
{
this.AddObject(payment.GetType().Name, payment);
}
}
关于c# - 关闭实体类以进行更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11425993/