1

In ASP.Net Core, I can get a list of all my entities, and find a specific one by name:

var entities = _context.Model.GetEntityTypes();
var entity = (from e in entities where e.Name == $"MyNamespace.Models.{entityname}" select e).FirstOrDefault();
Console.WriteLine(entity.Name);   //example output:  MyNamespace.Models.Car   

So I can access the entity name (or Model name) as a string, and now need to make that a class type for use by CsvHelper, because it requires that:

var records = csvReader.GetRecords<SomeClass>().ToList();  //typical use - not my code.

I tried to convert my entity to a Type as explained in this answer, so I do:

Assembly assem = typeof(MyNamespace.Models.Car).Assembly;
Type myType = Type.GetType(entity.Name);   //entity.Name example: MyNamespace.Models.Car
var records = csvReader.GetRecords<myType>().ToList();

Unfortunately, this results in:

 error CS0118: 'myType' is a variable but is used like a type

I don't understand why I get that error, or how to proceed.

trajekolus
  • 535
  • 6
  • 16
  • 1
    You can't do this - you're trying to use `System.Type` as generic type parameter. See similar question on how to [use `System.Type` as generic parameter](https://stackoverflow.com/a/4667999/997668) – Michael Jan 15 '20 at 08:14
  • Thanks, however I discovered that CsvHelper also supports calling like this: GetRecords(Type type). (Thank you Josh Close!). So I can use the type that was determined from string, and don't need to use a generic type parameter. – trajekolus Jan 15 '20 at 09:48

0 Answers0