Trying to reduce the code duplication by using generic methods to send a parameterized query to DB. Went for the following approach, but the query does not seem to resolve the implementation member's value. It works if the return type is strictly defined in GetQuery method, but then it's just back to square one. It also works if the CountryCode value is hardcoded inside GetQuery method.
Why doesn't the CountryCode use the value from the FrenchChocolate instance?
Interface:
public interface IChocolate
{
public string ManufacturerId { get; set; }
public string CountryCode { get; }
}
Implementation:
public class FrenchChocolate : IChocolate
{
public string ManufacturerId { get; set; }
public string CountryCode => "FR";
// ...other properties...
}
Query method (yes, it's ugly, feel free to propose a better way)
private static Expression<Func<T, bool>> GetQuery<T>(string manufacturerId) where T: IChocolate
{
T obj = (T)Activator.CreateInstance(typeof(T));
return c => c.ManufacturerId == manufacturerId && c.CountryCode == obj.CountryCode;
}
Method call:
var frenchChoc = await GetChocFromDb<FrenchChocolate>(GetQuery<FrenchChocolate>("123"));
This works, but defeats the purpose:
private static Expression<Func<**FrenchChocolate**, bool>> GetQuery<T>(string manufacturerId) where T: IChocolate
{
T obj = (T)Activator.CreateInstance(typeof(T));
return c => c.ManufacturerId == manufacturerId && c.CountryCode == obj.CountryCode;
}
This as well:
var frenchChoc = await GetChocFromDb<FrenchChocolate>(c => c.ManufacturerId == manufacturerId && c.CountryCode == "FR");