实体框架:跨不同 DbContext 共享实体 [英] Entity Framework : Sharing entities across different DbContexts
问题描述
我正在使用 EF6 开发插件应用程序,代码优先.
I'm developing a plugin application with EF6, code first.
我有一个名为 User
的实体的主要上下文:
I have one main context with an entity called User
:
public class MainDataContext : DbContext
{
public MainDataContext(): base("MainDataContextCS") {}
public DbSet<User> Users { get; set; }
}
然后是 PluginX 的另一个上下文,在另一个引用基础的项目上:
And then another context for PluginX, on another project which references the base one:
public class PluginDataContext : DbContext
{
public PluginDataContext () : base("MainDataContextCS") {
}
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.HasDefaultSchema("PluginX");
base.OnModelCreating(modelBuilder);
}
public DbSet<Booking> Bookings { get; set; }
}
这在同一个数据库(同一个连接字符串)上巧妙地创建了 PluginX.Bookings
表.
And this neatly creates, on the same Database (same connection string), the PluginX.Bookings
Table.
这里的问题是 Booking
实体包含对 User
实体的引用:
The problem here is that the Booking
entity contains a reference to User
entity:
public class Booking
{
public int Id { get; set;}
public virtual User CreationUser { get; set;}
public BookingStatus Status { get; set; }
}
当为插件上下文运行 Add-Migration
时,EF 将尝试创建另一个名为 PluginX.User
的 User
实体.
And when running Add-Migration
for the plugin context EF will try to create another User
entity called PluginX.User
.
如何解决?有没有办法在另一个 DbContext
中共享一个公共实体?
How can this be solved? Is there a way to share a common entity, in another DbContext
?
推荐答案
当您使用多个上下文时,您有两种选择:
When you work with multiple contexts you have two options:
- 将每个上下文视为单独的应用程序.想象一下,您的用户是您从 Web 服务获得的外部资源.您将无法为其添加外键.你要做的就是在你的表中只添加 userId,当你需要用户详细信息时调用外部服务来获取它们,或者在 Bookings 上下文中拥有用户的本地轻拷贝,你会不时更新从用户上下文.当您使用大型系统并且想要隔离各个部分时,这种方法非常有用(了解 DDD 和有界上下文)
- 除了您的 2 个上下文之外,使用整个模型(用户、预订等)创建第三个上下文.您将使用完整的上下文来创建迁移并维护数据库结构,但在应用程序中您将使用较小的上下文.这是一个非常简单的解决方案.使用单个上下文维护迁移很容易,并且仍然允许您在无法访问不相关实体的较小上下文中隔离数据库操作.
这篇关于实体框架:跨不同 DbContext 共享实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!