Domanda

In MSDN for Entity Framework 5 the .Find Methode is decribed as:

Uses the primary key value to attempt to find an entity tracked by the context. If the entity is not in the context then a query will be executed and evaluated against the data in the data source... http://msdn.microsoft.com/de-de/library/gg696418(v=vs.103).aspx

But, when i using '.Find' twice within the same context, it will hit the database also twice. I thought after the first try, the entity is stored in the context. (First Level Caching) What do i wrong ?

using (var myContext = new TestDbContext(connectionstring))
{
    var firstTry = myContext.Artikel.Find(20);
    Trace.WriteLine("First Try:" + firstTry.Id);

    var secondTry = myContext.Artikel.Find(20);
    Trace.WriteLine("Second Try:" + secondTry.Id);
}

Sql Profiler:

exec sp_executesql N'SELECT TOP (2) 
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name]
FROM [dbo].[Artikel] AS [Extent1]
WHERE [Extent1].[Id] = @p0',N'@p0 int',@p0=20

exec sp_executesql N'SELECT TOP (2) 
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name]
FROM [dbo].[Artikel] AS [Extent1]
WHERE [Extent1].[Id] = @p0',N'@p0 int',@p0=20
È stato utile?

Soluzione

Found it:

Since the 'id' column is of type long, i have to cast it to the right type.

var firstTry = myContext.Artikel.Find((long)20);
var secondTry = myContext.Artikel.Find((long)20);

Now it works as expected.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top