通用存储库 Linq2Sql 阻抗不匹配问题
我正在研究一个存储库模式,其中 API 如下所示:
var visitor = repository.Find(x => x.EmailAddress == credentials.EmailAddress &&
x.Password == credentials.Password);
其中访问者是域对象,x 代表该域对象。存储库上 Find 方法的方法签名是:
T Find(Func<T, bool> query);
这一切都很棒,直到我尝试将其与 Linq2Sql 一起使用,因为 linq2sql 创建自己的对象,因此当我想调用时:
context.visitors.FirstOrDefault(query);
存在类型不匹配,因为 linq2sql 需要一个函数它创建的类型而不是我传入的函数。
I am working on a repository pattern where the API look as follows:
var visitor = repository.Find(x => x.EmailAddress == credentials.EmailAddress &&
x.Password == credentials.Password);
where visitor is a domain object and x represents this domain object. The method signature of the Find method on the repository is:
T Find(Func<T, bool> query);
This is all wonderful until I attempt to use this with Linq2Sql because linq2sql creates its own objects and as a result when I want to call:
context.visitors.FirstOrDefault(query);
there is a type mismatch because linq2sql expects a function of the type it created and not the function I am passing in.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您需要将
Find
签名更改为:LINQ to SQL 需要将逻辑作为表达式树而不是普通委托,否则它无法计算出如何翻译将其转化为 SQL。
除此之外,恐怕还不是很清楚 - 听起来您没有为存储库和 LINQ to SQL 使用相同的域类。是这样吗?这听起来像是一个潜在的问题;至少它会让生活变得相当棘手。
Well to start with you'll need to change your
Find
signature to:LINQ to SQL needs to have the logic as an expression tree instead of a plain delegate, otherwise it can't work out how to translate it into SQL.
Beyond that, I'm afraid it's not terribly clear - it sounds like you're not using the same domain classes for your repository and LINQ to SQL. Is that right? That sounds like a potential problem; at the very least it's going to make life pretty tricky.