Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7034925
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T01:14:38+00:00 2026-05-28T01:14:38+00:00

I have this generic repository. /// <summary> /// Implémentation de base d’un dépositoire pour

  • 0

I have this generic repository.

 /// <summary>
/// Implémentation de base d'un dépositoire pour Entity Framework.
/// </summary>
/// <remarks>Entity Framework 4.1</remarks>
/// <typeparam name="TEntite">Entité spécifique.</typeparam>
public abstract class RepositoryBase<TEntity, TKey> : IRepository<TEntity>, IDisposable
    where TEntity : EntityBase<TKey>
    where TKey : class
{
    private readonly IContext _context;
    private ObjectContext _objectContext;
    private IObjectSet<TEntity> _objectSet;

    protected RepositoryBase(IContext context)
    {
        _context = context;
        _objectContext = _context.GetObjectContext();
        _objectSet = _objectContext.CreateObjectSet<TEntity>();
    }

    /// <see cref="IRepository.cs"/>
    public IEnumerable<TEntity> GetAll(Expression<Func<TEntity, object>> sortExpression)
    {
        if (sortExpression == null)
            sortExpression = x => x.Id;
        return _objectSet.OrderBy(sortExpression).AsEnumerable();
    }

    /// <see cref="IRepository.cs"/>
    public IEnumerable<TEntity> GetAll(int maximumRows, int startRowIndex, Expression<Func<TEntity, object>> sortExpression)
    {
        if (sortExpression == null)
            sortExpression = x => x.Id;
        return _objectSet.OrderBy(sortExpression).Skip(startRowIndex).Take(maximumRows).AsEnumerable();
    }

    /// <see cref="IRepository.cs"/>
    public TEntity SelectByKey(TKey key) 
    {
        if (key == null)
            throw new ArgumentNullException("La clé était NULL! Une clé est nécessaire pour récupérer un entité.");
        return _objectSet.SingleOrDefault(x => x.Id == key);
    }

Here the specific implementation…

public class ProductRepository : RepositoryBase<Product, int>, IProductRepository
{
    public ProductRepository(IContext context)
        : base(context)
    { }
    /// <see cref="IProductRepository.cs"/>
    public Product GetByName(string name)
    {
        return base.First(x => x.Name == name);
    }

    /// <see cref="IProductRepository.cs"/>
    public IEnumerable<Product> FindProduct(Specification<Product> specification)
    {
        throw new System.NotImplementedException();
    }
}

When i create a specific repository.. it say that Tkey must be a reference type but why ? Is there a way to make this generic repository work ? TKey was used in order to make the method SelectByKey accept a key type.

Edit #1:

If i remove the constrain then i have another problem… TKey cannot be compared with TKey using == as lambda expression in my SelectByKey method.

Edit #2:

Tried to use Equals and the syntax seem to be ok.

Edit #3:

Equals crash at runtime.. saying Tkey (which seem to be a System.Object) can’t use equals which doesnt seem logic since object have the equal method. I currently doesn’t have access to the real code but i did some test with this code below..

class Program
{
    static void Main(string[] args)
    {
        Test<TestEntity, int> t = new Test<TestEntity, int>();  
        t.TestMethod(5);
    }
}

class Test<TEntity, TKey>
    where TEntity : Entity<TKey>
{
    public Test()
    { }

    public TestEntity TestMethod(TKey id)
    {
        List<TestEntity> testEntity = new List<TestEntity>();
        testEntity.Add(new TestEntity(5));
        return testEntity.SingleOrDefault(x => x.Id.Equals(id));
    }
}

class Entity<TKey>
{
    public TKey Id { get; set; }
}

class TestEntity : Entity
{
    public TestEntity(int id)
    {
        Id = id;
    }
}

class Entity : Entity<int>
{
}

And it seem to work pretty well. So i will try later tonight.

Edit #4

Alright the exception i get is Canoot create a constant value of type “System.Object”. Only primary types such int32, string and guid are supported by this context.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T01:14:39+00:00Added an answer on May 28, 2026 at 1:14 am

    In your repository declaration

    public abstract class RepositoryBase<TEntity, TKey> : IRepository<TEntity>, IDisposable
        where TEntity : EntityBase<TKey>
        where TKey : class
    {
    

    you have specified the class constraint which will only allows reference types. See

    http://msdn.microsoft.com/en-us/library/d5x73970%28v=vs.80%29.aspx

    where T : class

    The type argument must be a reference type, including any class,
    interface, delegate, or array type. (See note below.)

    Remove the : class constraint to allow any type.

    Unless you’re engaged in a learning exercise, I would not try to build your repository from scratch. I would leverage off what others have done. When I wrote a repository framework, I wanted a GetById method that would work with primary keys of varying types (although not multiple column primary keys). When writing it, I found the following two posts especially helpful:

    C# LINQ to SQL: Refactoring this Generic GetByID method

    http://goneale.com/2009/07/27/linq-to-sql-generic-repository/

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this generic method in my repository: public T GetFirstOrDefault(Expression<Func<T, bool>> where, Expression<Func<T,
If I have a generic class like this: public class Repository<T> { public string
I have two generic save methods in a repository class: public void Save<T>(T entity)
I am using Entity Framework with the generic repository pattern. I have used the
I have this code (C#): using System.Collections.Generic; namespace ConsoleApplication1 { public struct Thing {
In my base class I have a generic method (ideally this would be a
I have a base class Parent like this: using System; using System.Collections.Generic; using System.Text;
I am writing a generic repository for entity framework and am confused as to
I am looking into creating an Entity Framework 4 generic repository for a new
I'm trying to write a generic repository for my Entity Framework based application. Here's

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.