c# - 通过针对接口(interface)编程来保留数据

标签 c# nhibernate linq-to-sql tdd domain-driven-design

我有一个 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
{
      ..
    }
}

阅读

  1. Optimizing Repository’s SubmitChanges Method

  2. How do you abstract out your persistence code when using LINQ to SQL?

  3. LINQ to SQL - mapping exception when using abstract base classes

最佳答案

您的存储库应该接受 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/

相关文章:

c# - 使用 "base"是不好的做法,即使它可能有利于可读性?

c# - 如何使用 EF6 获取 Controller 中任何属性的 [Display(Name ="")] 属性中的值

c# - Linq multiple where query with or operator

c# - 将 Func<T, int> 值插入 linq-2-sql 查询

c# - Take() 是否强制 LINQ 枚举结果 IEnumerable?

c# - 控制台图表绘制

c# - DataSource刷新后如何保留datagridview的 "schema"

c# - 用于分页到 HQL/Criteria 的 NHibernate SQL 查询

c# - 使用 nhibernate 有什么方法可以在接口(interface)中映射只读属性

c# - Linq 平等比较不起作用