Voglio recuperare più record fornendo array di chiave primaria e devo crearne un metodo generico per tutte le entità.
private DbSet<TEntity> _entities;
/// <summary>
/// Get entity by identifier
/// </summary>
/// <param name="id">Identifier</param>
/// <returns>Entity</returns>
public virtual TEntity GetById(object id)
{
return Entities.Find(id);
}
/// <summary>
/// Get entity by identifier
/// </summary>
/// <param name="id">Identifier</param>
/// <returns>Entity</returns>
public virtual List<TEntity> GetByIds(int id[])
{
// want to make it generic
return Entities.Where(x=>id.Contains(id));
}
/// <summary>
/// Gets an entity set
/// </summary>
protected virtual DbSet<TEntity> Entities
{
get
{
if (_entities == null)
_entities = _context.Set<TEntity>();
return _entities;
}
}
il problema qui è che le mie Entità non hanno colonne ID, ad esempio Product ha ProductId, Order ha OrderId. Non voglio cambiare le mie colonne db in Id.
Entities.Where(x=>id.Contains(id));
Voglio che le colonne delle mie entità siano le stesse di adesso. posso ottenere un metodo di ricerca generico con questa struttura db per trovare più record?
È possibile utilizzare i servizi di metadati forniti da EF Core come FindEntityType e FindPrimaryKey per ottenere il nome della proprietà PK. Quindi è possibile utilizzarlo per accedere al valore PK all'interno della query LINQ to Entities utilizzando un altro utile EF EF fornito dal metodo EF.Property .
Qualcosa come questo:
public virtual List<TEntity> GetByIds(int[] ids)
{
var idName = _context.Model.FindEntityType(typeof(TEntity))
.FindPrimaryKey().Properties.Single().Name;
return Entities
.Where(x => ids.Contains(EF.Property<int>(x, idName)))
.ToList();
}
È possibile avere nomi diversi nel modello dell'applicazione e nel modello del database. Dovrai mappare i tuoi ID modello al nome nel database:
Nel tuo Mapping avrai qualcosa di simile a questo per ogni entità: this.Property (t => t.Id) .HasColumnName ("ProductId");