将实体框架6与多个数据库架构一起使用,但使用一个DBContext [英] Using Entity Framework 6 with Multiple DB Schemas but using One DBContext

查看:147
本文介绍了将实体框架6与多个数据库架构一起使用,但使用一个DBContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用EF作为ORM的应用程序。该数据库曾经只有一个模式dbo,并且一切正常。我最近将表格组织成4种不同的模式。一个模式的某些表依赖于驻留在另一模式上的表。



在应用程序端,通过EF的所有数据库交互都不再起作用。代码会编译,架构在解决方案中可见,模型映射指向正确的架构,但是一旦我尝试向表中插入一行,它就无法正常工作。



<我已经看到了一些有关使用多个模式的文章,它们将需要使用多个DBContext,但是我宁愿使用一个DBContext。我所有的模式都有相同的所有者dbo,我看不到使用多个DBContext的原因。



有人知道是否有办法实现这一目标吗?

解决方案

您只能通过流畅的映射将每个表映射到其自己的模式。在您的 DbContext 子类型中,您应该覆盖 OnModelCreating (如果尚未这样做)并添加如下语句:

  modelBuilder.Entity< Department>()
.ToTable( t_Department, school);

您未明确映射的实体将被放置在默认的 dbo 模式,也可以通过以下方式提供自己的默认值:

  modelBuilder.HasDefaultSchema( sales ); 

(总结自此处


I have an application using EF as ORM. The database used to have one schema, dbo and everything was working fine. I recently organized my tables into 4 different schemas. Some tables of one schema have dependencies on tables that reside on a different schema. All seems to be valid on the SQL side.

On the app side all db interactions through EF are not working anymore. The code compiles, the schemas are visible in the solution, the model mappings point to the right schemas, but once I try to insert a row to a table it does not work.

I have seen a few posts about using multiple schemas will require using multiple DBContexts but I would rather use one DBContext. All my schemas have the same owner dbo and I do not see a reason of using multiple DBContexts.

Does anyone know if there is a way to achieve this?

解决方案

You can map each table to its own schema by fluent mapping only. In your DbContext subtype you should override OnModelCreating (if you haven't done so already) and add statements like this:

modelBuilder.Entity<Department>()  
    .ToTable("t_Department", "school");

Entities that you don't map like this explicitly will be placed in the default dbo schema, or you can provide your own default by

modelBuilder.HasDefaultSchema("sales");

(summarized from here)

这篇关于将实体框架6与多个数据库架构一起使用,但使用一个DBContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆