如果我设计我的数据库层以便我可以在 linq-to-sql 或 nhibernate 实现之间交换它,我必须针对接口编写代码。
这意味着 linq 和 nhibernate 之间的返回类型必须相同,即 List 等。
列表类型是否相同?
如果我设计我的数据库层以便我可以在 linq-to-sql 或 nhibernate 实现之间交换它,我必须针对接口编写代码。
这意味着 linq 和 nhibernate 之间的返回类型必须相同,即 List 等。
列表类型是否相同?
如果您封装您的数据库访问,例如使用存储库模式,您可以让存储库实现一个通用接口并让方法返回您选择用作返回类型的类型,例如 IEnumerable(T) 或 IList(T)。
由于 IList(T) 实现了 IEnumerable(T),因此在这个方向上没有问题。如果您有 IEnumerable(T),则可以使用 IEnumerable(T) 上的 ToList() 扩展方法来获取 List(T)。IQueryable(T) 将 IEnumerable(T) 实现到 ToList() 在这种情况下也可以正常工作。
像这样的东西:
public interface IFooRepository
{
IList<Foo> GetAll();
// ...
}
public class NHibernateFooRepository : IFooRepository
{
//...
public IList<Foo> GetAll()
{
return Session.CreateCriteria(typeof(Foo)).List<Foo>();
}
}
public class LinqToSqlFooRepository : IFooRepository
{
//...
public IList<Foo> GetAll()
{
var foos = from Foo f in context.Foos select f;
return foos.ToList();
}
}
IIRC, unless you'd want to use your db layer without LINQ query comprehensions (using the repository pattern), you should take a look at LINQ to NHibernate; in that case, you'd pretty much code against IQueryable<T>
results, which should translate most of the time. (Though you should really test this upfront, because every provider is different in its LINQ support.)
However, 1-* relations on your entity types will probably not share the same type by default (it's usually EntitySet<T>
in LINQ-to-SQL, and IList<T>
in NHibernate), but if you can force both LINQ-to-SQL and NHibernate to use IList<T>
or IEnumerable<T>
for such relations, this should work as well.
If you're only after compile time compatibility, the distinction between the various collection types should not be much of a problem, as long as you stick to the generic ones. For instance, if your NHibernate mapping uses IList<T>
and LINQ-to-SQL uses EntitySet<T>
, just stick to the IList<T>
methods, and you'll be safe.
Just watch out for lazy and eager loading differences of each framework.
NHibernate 默认为集合返回 IList,不幸的是,许多 linq 表达式对它们不起作用。我不确定是否有办法改变 NHibernate 返回类型,因为我还没有真正研究过。