Reviewing this question, how do I set Id to always mapped to primary key of a table? We have different tables, Product
, Customer
, each having different columns (ProductId
, CustomerId
) in the primary key, which don't always map to generic column Id. Need to ensure methods GetById, and GetAsyncById work below, or they may have to be changed if needed.
Currently reviewing reference below (I know generic repository is debated, manager told us to implement):
Generic Repository in C# Using Entity Framework
public class BaseRepository<T, TPrimaryKey> : IRepository<T, TPrimaryKey> where T : class, IEntity<TPrimaryKey>
{
public readonly DbContext _context;
protected virtual DbSet<T> Table { get; }
protected IQueryable<T> All => Table.AsNoTracking();
// This is causing an error
public int id => _context.Model.FindEntityType(typeof(T)).FindPrimaryKey().Properties.Single().Name);
public BaseRepository(DbContext context)
{
_context = context;
Table = _context.Set<T>();
}
public T Get(int id)
{
return Table.Find(id);
}
public async Task<T> GetAsync(int id)
{
return await Table.FindAsync(id);
}
// Other items below
public async Task DeleteAsync(T entity)
{
await Task.FromResult(_context.Set<T>().Remove(entity));
}
public IQueryable<T> GetAll()
{
return All;
}
public IQueryable<T> GetAllIncluding(params Expression<Func<T, object>>[] propertySelectors)
{
if (propertySelectors == null || propertySelectors.Length <= 0)
{
return All;
}
var query = All;
foreach (var propertySelector in propertySelectors)
{
query = query.Include(propertySelector);
}
return query;
}
}
We are currently using Net Core 2.2.
Error:
The type or namespace name '_context' could not be found (are you missing a using directive or an assembly reference?)
Will not use partial class method as it creates client side evaluation, and bringing the whole table into memory .
Update:
Answer from P Motameni below may not fully work. Need to make sure Id can be called as Property name, right now its classified as a string. Also need example so it will work with GetById, or maybe GetById method needs to be reconfigured.
Would it be something like this? Refer to a property name by variable
Or is there automated way with T4: to make primary keys Id in class? How to map table names and column name different from model in onmodelcreating method in Entity Framework -6?
The below line in your code has an extra parenthesis at the end after Name
Even if you remove the extra parenthesis, the code still will not compile because the Name type is string it is not an int. What you are capturing in this line is the name of the key not its value. Below code will compile fine and gives you the primary key name (id name).
Then use the name to get the id value.