简体   繁体   中英

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

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).

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.

Is there any function in EF that can allow something akin to :-

.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:

public partial class SomeEntity : IEntityWithName
{
}

You can then write a query that can use Name

Take a look at this story: Where can I find the 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. It has come in handy for me in the project I'm currently working on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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