我有一个 IBankAccount 接口(interface),我将把它传递给 ApplicationService。对帐户对象(在 ApplicationService 项目中)所做的更改需要保留在数据库中。存储库使用 IBankAccount 接口(interface)接收更改。如何将这些数据持久保存到数据库中?这是使用 LINQ to SQL 实现的。
注意:以下是 Scott 在 http://weblogs.asp.net/scottgu/archive/2007/06/29/linq-to-sql-part-3-querying-our-database.aspx 中的评论 “将接口(interface)添加到 LINQ to SQL 数据模型类。LINQ to SQL 类是部分类 - 这意味着您可以直接向它们添加接口(interface)。”
public class LijosSimpleBankRepository : ILijosBankRepository
{
public System.Data.Linq.DataContext Context
{
get;
set;
}
public virtual void UpdateAccount(DomainInterfaces.IBankAccount iBankAcc)
{
DBML_Project.BankAccount bankAccount;
}
}
namespace DomainInterfaces
{
public interface IBankAccount
{
int BankAccountID { get; set; }
string AccountType { get; set; }
System.Nullable<System.DateTime> OpenedDate { get; set; }
string Status { get; set; }
System.Nullable<int> AccountOwnerID { get; set; }
}
}
namespace DBML_Project
{
public class FixedBankAccount : BankAccount
{
//Note: BankAccount already implemnts IBankAccount
}
public class SavingsBankAccount : BankAccount
{
//Note: BankAccount already implemnts IBankAccount
}
//The auto generated calss is made as abstract
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.BankAccount")]
[InheritanceMapping(Code = "Fixed", Type = typeof(FixedBankAccount), IsDefault = true)]
[InheritanceMapping(Code = "Savings", Type = typeof(SavingsBankAccount))]
public abstract partial class BankAccount : INotifyPropertyChanging, INotifyPropertyChanged, DomainInterfaces.IBankAccount
{
..
}
}
阅读
最佳答案
您的存储库应该接受 BankAccount
- 而不是 IBankAccount
,因为 Linq-to-sql 不知道什么是 IBankAccount
并且编译器也不知道允许您存储它,而无需先将其转换为 BankAccount
(如果 IBankAccount
实例不是 BankAccount
,则在运行时显然会失败)。
一旦您拥有BankAccount
,您只需调用:
Context.BankAccounts.Add(account);
Context.SubmitChanges();
关于c# - 通过针对接口(interface)编程来保留数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11291202/