2

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.

John Mitchell
  • 9,653
  • 9
  • 57
  • 91
  • 3
    Why not just create a INamedEntity { string Name } and where TEntity : INamedEntity and make all your entities implement TEntity – Carlos Muñoz Jan 05 '15 at 19:37
  • Can you use [Anonymous Types](http://msdn.microsoft.com/en-us/library/bb397696.aspx)? – Bob. Jan 05 '15 at 19:49

2 Answers2

5

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

Carlos Muñoz
  • 17,397
  • 7
  • 55
  • 80
Grzegorz W
  • 3,487
  • 1
  • 21
  • 21
0

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.

Community
  • 1
  • 1
GBreen12
  • 1,832
  • 2
  • 20
  • 38