I have a simple web application which allows an user to upload 2 .csv-files containing certain data. To persist the data I use the Entity Framework
in two different Import-methods
.
First Import-method
public void ImportOne(string path)
{
StreamReader sr = new StreamReader(path);
using (var db = new ContextEv("RndContext"))
{
db.Database.ExecuteSqlCommand("DELETE FROM TableA");
db.Database.ExecuteSqlCommand("DELETE FROM TableB");
while (!sr.EndOfStream)
{
string[] data = sr.ReadLine().Split(';');
string houseId = data[0];
House house = new House()
{
HouseId = houseId,
};
House dummy = db.Houses.Find(houseId);
if (!dummy.HouseId.Equals(house.HouseId))
{
db.Houses.Add(house);
}
}
}
}
}
This line fails: House dummy = db.Houses.Find(houseId);
with the following exception:
The type of one of the primary key values did not match the type defined in the entity. See inner exception for details.\r\nParametername: keyValues
ErrorContext of InnerException:
keyword 'AS', line 1, column 22
ErrorDescription of InnerException:
The query syntax is not valid.
Alright, I checked if really the type is the problem here. However I haven't found anything wrong.
The "funny" thing about it is, that I use the same Find-method in another Import-method and it works without any exception!
using (var db = new ContextEv("RndContext"))
{
db.Database.ExecuteSqlCommand("DELETE FROM TableC");
db.Database.ExecuteSqlCommand("DELETE FROM TableD");
StreamReader sr = new StreamReader(path);
while (!sr.EndOfStream)
{
string[] data = sr.ReadLine().Split(';');
string houseId = data[5];
House house = db.Houses.Find(houseId);
...
...
db.SaveChanges();
}
}
I wasn't sure which code is really needed for you to answer my question but I'd be very happy to post more if someone asks for a particular code.
UPDATE 1 ANSWER TO user89861
'db.Houses.ToList().Find(h => h.HouseId == houseId)' threw an exception of type 'System.NullReferenceException'
" bei System.Data.Entity.Internal.Linq.InternalQuery
1.GetEnumerator()\r\n
1.GetEnumerator()\r\n bei System.Data.Entity.Infrastructure.DbQuery
bei System.Data.Entity.Internal.Linq.InternalSet1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()\r\n bei System.Collections.Generic.List
1..ctor(IEnumerable1 collection)\r\n bei System.Linq.Enumerable.ToList[TSource](IEnumerable
1 source)"