我想为单个实体类型创建两个表。表是相似的,除了第二个表可能会丢失一些外键(顺便说一句,在该问题的上下文中这不是很重要)。
第一个表将以常见的方式使用(选择查询、少量插入查询等)。
第二个表是临时的,将用于批量插入操作(即,首先我使用 SqlBulkCopy 将数据插入到临时表中,接下来我使用 MERGE 查询将项目更新插入到第一个表中)。这种方法使我能够非常快速地更新插入数千条记录。
那么,强制 EF7 为同一实体创建两个相同表的最佳方法是什么?
我发现了类似的问题:Use same type against two identical tables in EF Code First 但似乎那个人(提出问题的人)想要具有相同实体的多个 DbSet。我的情况略有不同 - 我只想自动创建表,仅此而已。
最佳答案
好吧,看来我可以自己回答这个问题了。
所以,实际上我有一个丑陋的解决方案:使用简单的继承,我可以创建相同的实体,该实体可用于在同一个 DbContext 中创建另一个 DbSet。
此外,为了避免使用 EF 继承策略,我需要保留基本类型未映射(即,我不需要在数据库模式中进行任何与继承相关的更改)。该要求迫使我创建基类(将取消映射)和两个继承者(一个用于主表 DbSet,另一个用于临时表 DbSet)。
这种方法使我能够避免相同类型的问题,更重要的是,使我能够保持表架构完全相同而不会出现任何问题。
示例:
/// <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; }
}
关于c# - 如何使用 EF7 Fluent API 为单个 POCO 创建两个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34251053/