[英]Entity framework query without lambda expression
So I'm writing a 'semi-generic' class that fits the same pattern over and over again with the signature 因此,我正在写一个“半通用”类,该类一次又一次地符合签名
public class BaseSupportRepo<TEntity, TDto> where TEntity : class where TDto : class
All of the repos that use this class have one property which is Name
所有使用此类的仓库都具有一个名为
Name
属性。
What I want to do is write a function that will return a .Single() if a name matches some input (however name is not a primary key). 我想做的是编写一个函数,如果名称匹配某些输入(但是名称不是主键),则该函数将返回.Single()。
Now if this was a non generic function it'd be easy since 现在,如果这是一个非泛型函数,那将很容易,因为
.Single(g => g.Name == name)
However because this is a generic function the .Name property cannot be used since TEntity may not have any property Name. 但是,因为这是通用函数,所以不能使用.Name属性,因为TEntity可能没有任何属性Name。
Is there any function in EF that can allow something akin to :- EF中是否有任何功能可以使类似于以下内容:
.Single(string key, string value)
This would allow me to get around this requirement. 这将使我绕开这一要求。
Create interface: 创建界面:
public interface IEntityWithName
{
string Name { get; set;}
}
And change Your repo to: 并将您的回购更改为:
public class BaseSupportRepo<TEntity, TDto> where TEntity : class, IEntityWithName
where TDto : class
If You have a generated code using edmx file you can change your T4 template that generates Your classes to implement IEntityWithName
or create partial classes like this: 如果您具有使用edmx文件生成的代码,则可以更改生成您的类的T4模板以实现
IEntityWithName
或创建如下的部分类:
public partial class SomeEntity : IEntityWithName
{
}
You can then write a query that can use Name
然后,您可以编写一个可以使用
Name
的查询
Take a look at this story: Where can I find the System.Linq.Dynamic dll? 看一下这个故事: 在哪里可以找到System.Linq.Dynamic dll? .
。 Dynamic.cs was written by someone at Microsoft I believe and it allows you to write Linq queries using strings rather than lambdas.
我相信Dynamic.cs是由Microsoft的某人编写的,它使您可以使用字符串而不是lambda来编写Linq查询。 It has come in handy for me in the project I'm currently working on.
在我目前正在从事的项目中,它对我很方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.