-1

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?

UnusualWays
  • 177
  • 1
  • 2
  • 11
  • *How do I determine the current implementation at runtime?* and what it will give you? ... your error is compile time error not runtime ... it `someProperty` is common for all `IDataModel` then move it into `IDataModel` ... if not ... you have to write different code for different classes – Selvin Mar 18 '21 at 08:48

1 Answers1

-2

Have a look at the curiously recurring template pattern; it is useful for creating child objects with the right type. Maybe also look at this discussion.

Daniel
  • 321
  • 3
  • 10
  • 1
    Please don't link to external sources without first putting the salient content in your answer. Links in answers should only provide supporting evidence. – Enigmativity Mar 18 '21 at 09:16
  • Well, the name of the pattern is the real information here, summarizing it is not necessary, I think. Besides, the linked SO question / answer does that job. – Daniel Mar 18 '21 at 09:43
  • No, not at all. You really should pay attention to those with a significant amount of rep here - we know how to help you to get more rep. – Enigmativity Mar 18 '21 at 09:54
  • 1
    That is no motivation, just makes me feel patronized. – Daniel Mar 18 '21 at 11:10