Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to implement a generic GetById method using Entity Framework 4 and the Repository Pattern?
    primarykey
    data
    text
    <p>I have a generic repository and would like to implement a generic GetById method. This is my repository interface so far:</p> <pre><code>public interface IRepository&lt;T&gt; where T : EntityObject { void Add(T entity); void Delete(int id); void Delete(T entity); IEnumerable&lt;T&gt; Find(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); T SingleOrDefault(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); IEnumerable&lt;T&gt; GetAll(); T GetById(int id); void Save(); T Single(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); } </code></pre> <p>I am using the Entity Framework 4.1. Lots of the solutions I found were using an abstract base class of interface for an IEntity class which the entities have to inherit from in order to perform the Id lookup.</p> <p>Instead of having to implement an interface for all my classes I was trying to use this bit of code:</p> <pre><code>T entity = _objectSet.Where( x =&gt; x.EntityKey.EntityKeyValues .Select(v =&gt; v.Value.Equals(id)).Count() == 1).First(); </code></pre> <p>However when trying to use the method I receive an exception:</p> <p><code>The specified type member 'EntityKey' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.</code></p> <p>Could someone tell me how I can get this to work?</p> <p><strong>Update 1</strong></p> <p>The members _objectContext and _context are declared like this:</p> <pre><code>private readonly ObjectContext _context; private readonly IObjectSet&lt;T&gt; _objectSet; </code></pre> <p>Thanks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload