lundi 7 novembre 2022

EF Core: How to get identity key value generically using reflection or keyattribute

Good day, currently working on an existing system that has over a 200 lookups which are stored in the database, e.g.

public class FruitLookup
{
    [Key]
    public int FruitId {get;set;}

    public string FruitCode {get;set;}

    public string Description {get;set;}
}

Each lookup has a code and description accordingly and each has a strategy class to get its data and only the code and description is exposed as below:

public class FruitLookupStrategy : LookupStrategy
{
   public IQueryable<LookupBase> GetLookupData()
   {
        return this.GetLookupData()
            .Select(_ => new LookupDataSet 
            { 
                Code = _.FruitCode, 
                Description = _.Description 
            })
            .OrderBy(_ => _.Value)
            .AsQueryable();
   }
}
public class LookupBase
{
    public int Id {get;set;} // new mapping property added
    public string Code {get;set;}
    public string Description {get;set;}
}

this.GetLookupData... is just an EF call to select the lookup table. It exists in the base class LookupStrategy

The new requirement is to expose the Id for each of these lookup tables, because codes can be the same, and we the Id properties will be mapped on our new front ends as the value expressions.

Is there a way to achieve this in a more clever way that going to edit over 200 lookup strategy helper files either using generics or reflection? Below is the undesired approach of adding a new mapping of Id to each strategy class:

public class FruitLookupStrategy : LookupStrategy
{
   public IQueryable<LookupBase> GetLookupData()
   {
        return this.GetLookupData()
            .Select(_ => new LookupDataSet 
            { 
                Code = _.FruitCode, 
                Description = _.Description, 
                Id = _.FruitId 
            })
            .OrderBy(_ => _.Value)
            .AsQueryable();
   }
}




Aucun commentaire:

Enregistrer un commentaire