Entity Framework throws an exception when using the Find-method

I have a simple web application that allows the user to upload 2 CSV files containing specific data. To save the data I use Entity Frameworkin 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 does not work: House dummy = db.Houses.Find(houseId);with the following exception:

The type of one of the primary key values ​​does not match the type defined in the object. See Internal Exception for more details. \ R \ nApparent Name: keyValues

ErrorContext of InnerException:

keyword "AS" row 1 column 22

ErrorDescription InnerException:

The request syntax is invalid.

Well, I checked if the problem is really here. However, I did not find anything wrong.

"" , Find Import-, - !

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();
                }
            }

, , , , - .

1 user89861

'db.Houses.ToList(). (h = > h.HouseId == houseId)' 'System.NullReferenceException'

"bei System.Data.Entity.Internal.Linq.InternalQuery 1.GetEnumerator()\r\n
bei System.Data.Entity.Internal.Linq.InternalSet
1.GetEnumerator()\\ System.Data.Entity.Infrastructure.DbQuery 1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()\r\n bei System.Collections.Generic.List 1..ctor(IEnumerable 1 collection)\r\n bei System.Linq.Enumerable.ToList[TSource](IEnumerable 1 )"

+4
3

Find() null, , :

House house = db.Houses.Find(obj => {return obj.HouseId == houseId;});
if (house == null) continue; //go to next iteration
0

.find() , , , , (, , ).


.Where() / .FirstOrDefault(), .find(), , .

var usr=db.Employees.Where(
    x => x.FirstName=="James" && x.LastName=="Bond").FirstOrDefault();

:

var usr=db.Employees.FirstOrDefault(
    x => x.FirstName=="James" && x.LastName=="Bond");

Null, .

, , - , , , : .Where.

, intellisense , , " ".

. , .Where .FirstOrDefault , .Find, ( , SO, ) .

, .Any(), .Single(), .First(), .Where() ( ...OrDefault() pendents) SQL- , , , ad-hoc .

, ,, . LinqPad , EF SQL ( Northwind ):

SELECT TOP (1) 
[Extent1].[EmployeeID] AS [EmployeeID], -- primary key (PK)
[Extent1].[LastName] AS [LastName], [Extent1].[FirstName] AS [FirstName], 
[Extent1].[Title] AS [Title], [Extent1].[TitleOfCourtesy] AS [TitleOfCourtesy], 
[Extent1].[BirthDate] AS [BirthDate], [Extent1].[HireDate] AS [HireDate], 
[Extent1].[Address] AS [Address], [Extent1].[City] AS [City], 
[Extent1].[Region] AS [Region], 
[Extent1].[PostalCode] AS [PostalCode], [Extent1].[Country] AS [Country], 
[Extent1].[HomePhone] AS [HomePhone], [Extent1].[Extension] AS [Extension], 
[Extent1].[Photo] AS [Photo], [Extent1].[Notes] AS [Notes], 
[Extent1].[ReportsTo] AS [ReportsTo], [Extent1].[PhotoPath] AS [PhotoPath]
FROM [dbo].[Employees] AS [Extent1]
WHERE (N'James' = [Extent1].[FirstName]) AND (N'Bond' = [Extent1].[LastName])

, , , , , .

.find() EmployeeID, (PK). , , .find() (.Where(), .Single(), .First() .Any()).


( , , if):

string houseId = data[0];
House dummy = db.Houses.FirstOrDefault(x=>x.HouseId==houseId);
if (dummy==null)
{
    House house = new House()
    {
        HouseId = houseId
    };
    db.Houses.Add(house);
}

, , .Any():

string houseId = data[0];
if (!db.Houses.Any(x => x.HouseId == houseId))
{
    House house = new House()
    {
        HouseId = houseId,
    };
    db.Houses.Add(house);
}

, , ( ).

0

I managed to fix this strange error. In Context-Constructor I just added

public ContextEv(string dbName) : base("name=" + dbName)
{
           //Database.SetInitializer(new DropCreateDatabaseAlways<ContextEv>());
}

However, at first I had to delete each table manually, because the code above did not do this. And after he missed it, I had to comment on the code and run it again so that the table looks (why, I really don't know .. maybe some of you know).

Thank you all for your help! I really learned something with your answers.

0
source

Source: https://habr.com/ru/post/1616124/


All Articles