Of course, there is a way to introduce temporary tables in Entity Framework context.
But, before I started explaining how to use temp tables in Entity Framework context I want to explain what was my goal in order to achieve such a feature.
So, let's start...
My goal was to add an entity that represents temp table from DB and write a LINQ query to load the data into it. Later on, in code, I wanted to use it in LINQ as I'm using any other entity that represents a permanent table.
Seems like steps to achieve it are very straightforward looking from T-SQL perspective:
- create a temp table
- load the data into it
- use it later in the code
but from C# it's not so trivial because I had to find out:
- how to get translated from LINQ T-SQL query with all the parameters
- how to declare entity that represents temp table in DB and distinguish it from other entities
- how to load data into temp entity
- how to get parameter order from LINQ query being used to load the data into temp table
- how to handle dependencies between temp tables
- how to attach prepared "temp query" into DbContext
- ....
Anyway, after some digging through the Entity Framework 6 source code and searching on the Internet I found what do I need and, finally, I've got proof and concept followed by the first version.
Here is a very simple usage:
declare a temp entity
[Table("#tempAddress")]
public class AddressTempTable : ITempTable
{
[Key]
[TempFieldTypeAttribute("int")]
public int AddressId { get; set; }
[TempFieldTypeAttribute("varchar(200)")]
public string StreetName { get; set; }
}
add an entity that represents temp table in DbSet collection
public DbSet<AddressTempTable> AddressesTempTable { get; set; }
load the data into it
var tempAddressQuery = entityContext.Addresses.Select(a => new AddressTempTableDto { AddressId = a.AddressId , StreetName = a.StreetName });
Attach and use it
var addressList = entityContext
.WithTempTableExpression<EntityContext>(tempAddressQuery)
.AddressesTempTable.Join(entityContext.Addresses,
(a) => a.AddressId,
(aa) => aa.AddressId,
(at, a) => new
{
AddressId = at.AddressId,
StreetName = a.StreetName
}).ToList();
I published my solution in a form of Nuget package called - EF6TempTableKit.
Here is a very basic example.
Source code is available here .