【发布时间】:2012-06-29 13:34:13
【问题描述】:
我有以下存储库。我使用工厂在 LINQ 2 SQL 生成的类和域对象之间建立了映射。
以下代码将起作用;但我发现了两个潜在问题
1) 在更新语句之前使用 SELECT 查询。
2) 它需要更新所有列(不仅是更改的列)。这是因为我们不知道域对象中的所有列都发生了哪些变化。
如何克服这些缺点?
注意:可能存在基于特定列更新执行的场景(如触发器)。所以我不能不必要地更新列。
参考:
代码
namespace RepositoryLayer
{
public interface ILijosBankRepository
{
void SubmitChangesForEntity();
}
public class LijosSimpleBankRepository : ILijosBankRepository
{
private IBankAccountFactory bankFactory = new MySimpleBankAccountFactory();
public System.Data.Linq.DataContext Context
{
get;
set;
}
public virtual void SubmitChangesForEntity(DomainEntitiesForBank.IBankAccount iBankAcc)
{
//Does not get help from automated change tracking (due to mapping)
//Selecting the required entity
DBML_Project.BankAccount tableEntity = Context.GetTable<DBML_Project.BankAccount>().SingleOrDefault(p => p.BankAccountID == iBankAcc.BankAccountID);
if (tableEntity != null)
{
//Setting all the values to updates (except primary key)
tableEntity.Status = iBankAcc.AccountStatus;
//Type Checking
if (iBankAcc is DomainEntitiesForBank.FixedBankAccount)
{
tableEntity.AccountType = "Fixed";
}
if (iBankAcc is DomainEntitiesForBank.SavingsBankAccount)
{
tableEntity.AccountType = "Savings";
}
Context.SubmitChanges();
}
}
}
}
namespace DomainEntitiesForBank
{
public interface IBankAccount
{
int BankAccountID { get; set; }
double Balance { get; set; }
string AccountStatus { get; set; }
void FreezeAccount();
}
public class FixedBankAccount : IBankAccount
{
public int BankAccountID { get; set; }
public string AccountStatus { get; set; }
public double Balance { get; set; }
public void FreezeAccount()
{
AccountStatus = "Frozen";
}
}
}
【问题讨论】:
-
"需要更新所有列"。这对性能的影响到底是什么?你测量过这个吗?
-
@Steven 这是我的假设。毕竟,从逻辑上讲,这是不必要的努力。从 SQL 的角度来看,可能并非如此。此外,可能存在基于列更新执行的场景(如触发器)。所以我不能不必要地更新列。 sqlteam.com/forums/topic.asp?TOPIC_ID=113917
-
除非你“继承”了数据库设计,否则我认为你真的必须重新考虑触发器的这种使用。如果您只是因为记录更改而需要触发,请在表中使用时间戳并让更新触发器对此做出响应。
标签: c# .net design-patterns linq-to-sql domain-driven-design