试图将Linq to SQL用于我在家工作的小项目。我已经使用dbmetal.exe(来自DBLinq项目)针对本地MySQL数据库生成了上下文代码和所有实体类。通用表<TEntity>
一切都很好,但我想抽象一些冗余代码,我遇到了试图这样做的问题。
基本上我所有的实体在我的上下文类中都是Table<TEntity>
类型。例如,我有Table<User>
和。
当我构建存储库行为的各种接口时,我意识到存在一些对每个实体都非常冗余的方法。例如,ID字段:
User findById(int id);
Calendar findById(int id);
我设计我的表,以便它们都具有共同的[ID,dateCreated会,DATEUPDATED] 3个字段。由于这些字段很常见,我想要有一个共同的行为,而不是为每个实体重写这些方法。
所以我做了我的仓库类(UserRepository,CalendarRepository)会沿用这样定义一个共同的“信息库”类:
public class Repository<T> : IDisposable, IRepository<T> where T : class
{
protected MyContext context;
private DbLinq.Data.Linq.Table<T> currentTable;
protected Repository() {
context = new MyContext();
Type currentType = this.GetType().GetGenericArguments()[0];
currentTable = //Set currentTable based on currentType. e.g.: currentTable = context.User;
}
#region IRepository<T> Members
public T findById(int? id)
{
return currentTable.SingleOrDefault(d => d.ID == id);
}
public T findByDateCreated(DateTime dateCreated)
{
return currentTable.SingleOrDefault(d => DateTime.Equals(dateCreated, d.DateCreated));
}
public T findByDateUpdated(DateTime dateUpdated)
{
return currentTable.SingleOrDefault(d => DateTime.Equals(dateUpdated, d.DateUpdated));
}
public T insert(T domainObject)
{
currentTable.InsertOnSubmit(domainObject);
return domainObject;
}
public T save(T domainObject)
{
context.SubmitChanges();
return domainObject;
}
#endregion
#region IDisposable Members
public void Dispose()
{
if (context != null)
context.Dispose();
}
#endregion
}
那么事实证明,这是比我想象的更困难。当我尝试设置:
currentTable = (Table<T>)context.User;
我得到以下错误:
Cannot convert type 'DbLinq.Data.Linq.Table<Models.Domain.User>' to 'DbLinq.Data.Linq.Table<T>'
隐式转换也不起作用。
任何人都曾经做过类似的成功?如果我必须让所有的Repository类实现相同的findById方法,并且代码完全相同,那将会非常难过......我确信有一种方法可以不这样做,我无法找到它。 :)
它在编译时或运行时失败吗? – eglasius 2009-11-08 00:06:23