I have a process to read a CSV file to database. This csv is over 600 Mb so I can't set all in memory. I use generic pattern to achieve this but I have problems on casting:
Here I Read the file
using (var fs = File.OpenText(Path.Combine(FolderContainer, filename)))
{
var csvConfiguration = new CsvConfiguration
{
HasHeaderRecord = true,
Delimiter = ","
};
using (var csvReader = new CsvReader(fs, csvConfiguration))
{
csvReader.Configuration.RegisterClassMap(CsvMapping.CsvMapping.RetrieveMapType(type));
var list = csvReader.GetRecords(type);
// Console.WriteLine(list.First());
dynamic repository = Activator.CreateInstance(typeof(Repository<>).MakeGenericType(type), UnitOfWork);
// var activities = new Repository<Activity>(UnitOfWork);
repository.InsertAllOnSubmit(list.Take(100));
repository.SubmitChanges();
}
}
I use the Take(100) for my tests purpose, I use a Unit of work InMemory.
Here is the Repository method called
public void InsertAllOnSubmit(IEnumerable<T> entities)
{
_source.InsertAllOnSubmit(entities);
}
public void InsertAllOnSubmit(IEnumerable<object> entities)
{
// foreach (var entity in entities)
// {
// InsertOnSubmit((T) entity);
// }
this.InsertAllOnSubmit((IEnumerable<T>)entities);
}
When I execute my test, I have a castException
System.InvalidCastException : Unable to cast object of type '<TakeIterator>d__3a`1[System.Object]' to type 'System.Collections.Generic.IEnumerable`1[KboOpenDataData.Activity]'.
I Try to add a AsEnumerable() or a ToList() after the Take(100) as readed on http://blog.codelab.co.nz/2009/12/22/unable-to-cast-object-of-type-issue/ with no success. And I don't want to use ToList because I can't set the whole file in memory due to size.
I comment the lines where I used a foreach in the repository class, the foreach works but it's very very slow.
Any advices to success the cast?
Try following -
repository.InsertAllOnSubmit(list.Take(100).Cast<Activity>());
Cast
extension method lets you cast enumerables from one type to another (Assuming of course that the cast is valid.. which is what you expect with explicit casts).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.