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.

2
  • 3
    Why not just create a INamedEntity { string Name } and where TEntity : INamedEntity and make all your entities implement TEntity Commented Jan 5, 2015 at 19:37
  • Can you use Anonymous Types? Commented Jan 5, 2015 at 19:49

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately I can't get at the Entity classes since they are generated using a tool :|
If entities are partial classes you can put the interface in a partial class on your own file
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.