简体   繁体   English

通用存储库Linq2Sql阻抗不匹配问题

[英]Generic Repository Linq2Sql impedence mismatch problem

I am working on a repository pattern where the API look as follows: 我正在研究API如下的存储库模式:

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. 其中visitor是一个域对象,x表示该域对象。 The method signature of the Find method on the repository is: 存储库中Find方法的方法签名为:

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: 直到我尝试将其与Linq2Sql一起使用,这一切都是奇妙的,因为linq2sql创建了自己的对象,因此在我想调用时:

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. 类型不匹配,因为linq2sql期望使用它创建的类型的函数,而不是我传入的函数。

Well to start with you'll need to change your Find signature to: 首先,您需要将“ Find签名更改为:

T Find(Expression<Func<T, bool>> query);

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. LINQ to SQL需要将逻辑作为表达式树,而不是简单的委托,否则无法弄清楚如何将其转换为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. 除此之外,恐怕还不是很清楚-听起来您的存储库和LINQ to SQL没有使用相同的域类。 Is that right? 那正确吗? That sounds like a potential problem; 听起来像是潜在的问题; at the very least it's going to make life pretty tricky. 至少它将使生活变得非常棘手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM