I receive data from a DB. There will be only one model at a time which I call currentModel
from now on. The type of model received must be determined at runtime. Therefore, I implemented an Interface for the models IDataModel
. Each possible model implements IDataModel
. There is a variable which holds the currentModel
. In order to make it generic I defined it as IDataModel
. Here is the code so far.
public async Task<List<T>> LoadData<T, U>(string sql, U parameters, string connectionString)
{
using (IDbConnection connection = new SqlConnection(connectionString))
{
var rows = await connection.QueryAsync<T>(sql, parameters);
return rows.ToList();
}
}
private IDataModel currentModel;
private List<IDataModel> queryResult;
if (someCondition)
{
currentModel = newSpecificModel();
sql = someQuery;
}
else ....
queryResult = await _data.LoadData<IDataModel, dynamic>(sql, new {}, config.GetConnectionString("default"));
if (queryResult.Count == 1)
{
currentModel= queryResult.First();
}
else
{
// Do error handling here if more than one row is returned from the query
}
Now when I try to access some property I get an error: IDataModel does not contain a definition for someProperty
currentModel.someProperty
How do I determine the current implementation at runtime? I mean I could create a variable for each possible model. But is there a more elegant way?
EDIT
Nailed the problem down to that this wont work:
List<Interface> = List<Implementation>
See this post.
Whats an approach to solve this?