iantukic
iantukic

Reputation: 87

Set new Guid id in Repository method

I'm trying to implement generic repository pattern and I have a small problem with my "Add" method:

  public class GenericRepository<T> where T : class
  {
    private readonly DbContext _context;
    private DbSet<T> DbSet;

    public async Task AddAsync(T t)
    {
        _context.Set<T>().Add(t);
        await _context.SaveChangesAsync();
    }
   }

This method works, but since "Id" property of my entity is Guid I get all zeros as Id.

So in my method I should set new Guid as Id:

t.Id = Guid.NewGuid();

but I'm not sure how can I set Id property of my entity via generics.

Upvotes: 0

Views: 1305

Answers (2)

Paul
Paul

Reputation: 3306

The idea of a "generic repository pattern" is a red flag in my mind. Repository patterns usually contain very specific methods, such as GetTopTenContributingUsers or AddNewUser, to prevent leaky abstractions back to the caller and to abstract the data layer away. DbContext is a pretty generic pattern already so trying to wrap another generic abstraction around it seems a little misguided on the face of it.

You can't set a property using generics, but as @MotoSV said you could add one to your each of you entities using a common interface. Bear in mind though that if your table is insert heavy then using a Guid as a primary key in the database table is generally discouraged as they do not index well and will have a negative performance impact over time.

Upvotes: 0

MotoSV
MotoSV

Reputation: 2368

You could have all entities implement an interface and add this interface as a constraint on T.

For example:

public interface IEntity
{
  Guid Id { get; set; }
}

public class MyEntity : IEntity
{
  public Guid Id { get; set; }
}

public class GenericRepository<T> where T class, IEntity
{
  public async Task AddAsync (T t)
  {
    ...
    T.Id = Guid.NewGuid();
    ...
  }
}

Upvotes: 1

Related Questions