How to create two tables for single POCO using EF7 fluent API?

c# ef-code-first entity-framework entity-framework-core

Question

I want to create two tables for single entity type. Tables are similar except second one can miss some foreign keys (btw, it is not very important in context of that question).

First table would be used in a common way (select queries, little insert queries and so on).

Second table is temporary and would be used for bulk-insert operations (i.e. first I use SqlBulkCopy in order to insert data into temp table and next I use MERGE query to upsert items into first table). That approach allows me to upsert thousands of records very fast.

So, what is the best way to force EF7 to create two identical tables for same entity?

I have found similar question: Use same type against two identical tables in EF Code First But it seems like that guy (one who ask the question) want to multiple DbSets with same entity. My case is little different - I just want to automate table creation, nothing more.

Accepted Answer

Ok, it seems like I can answer that question by myself.

So, actually I have one ugly solution: using simple inheritance I can create identical entity that can be used for create another DbSet in same DbContext.

Also, in order to avoid engagement of EF inheritance strategy, I need to leave base type unmapped (i.e. I don't need any inheritance-connected changes in DB schema). That requirement force me to create base class (that would be unmapped) and two inheritors (one for primary table DbSet and another for temp table DbSet).

That approach allows me to avoid same-type-problem and, more important, allows me to keep table schemas exactly the same without any problems.

Example:

/// <summary>
/// Base entity, not used by EF at all - intended to define properties only.
/// </summary>
public class MyEntityBase
{
    public int Id { get; set; }
    public string Name { get; set; }
}

/// <summary>
/// That entity used to create primary table and used by app logic.
/// </summary>
public class MyEntity : MyEntityBase
{
}

/// <summary>
/// That entity used to create temp table only.
/// </summary>
public class MyTempEntity : MyEntityBase
{
}

/// <summary>
/// Here is our DB context with two DbSets...
/// </summary>
public class MyDbContext : DbContext
{
    /// <summary>
    /// That DbSet should be used by app logic.
    /// </summary>
    public DbSet<MyEntity> MyEntities { get; set; }

    /// <summary>
    /// That DbSet will force EF to create temp table.
    /// App logic shouldn't interact with it in common way 
    /// (only SqlBulkCopy and some hand-written queries) 
    /// so it is not public.
    /// </summary>
    protected DbSet<MyTempEntity> MyTempEntities { get; set; }
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why