sab*_*ber 17 c# sql-server entity-framework cross-database
有没有办法在Entity Framework中实现跨数据库查询?让我们假设我有两个实体用户和帖子,用户实体在database1中,Post在数据库2中,这意味着这些实体在不同的数据库中.我应该如何获得实体框架中的用户帖子?
小智 23
我知道这是一个旧线程,但实际上.这个有可能.如果数据库在同一台服务器上,那么您需要做的就是使用a DbCommandInterceptor.
例如,如果我附加一个DbCommandInterceptor,MyContext我可以拦截所有命令执行,并用我的全数据库路径替换查询中的指定表.
public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
// Here, I can just replace the CommandText on the DbCommand - but remember I
// want to only do it on MyContext
var context = contexts.FirstOrDefault() as MyContext;
if (context != null)
{
command.CommandText = command.CommandText
.Replace("[dbo].[ReplaceMe1]", "[Database1].[dbo].[Customers]")
.Replace("[dbo].[ReplaceMe2]", "[Database2].[dbo].[Addresses]")
.Replace("[dbo].[ReplaceMe3]", "[Database3].[dbo].[Sales]");
}
base.ReaderExecuting(command, interceptionContext);
}
Run Code Online (Sandbox Code Playgroud)
关于这种方法的好处还在于EF模型映射仍然可以正常工作并且尊重Column属性,不需要视图,并且不需要存储过程.
And*_*mar 11
您可以使用ExecuteStoreQuery,例如:
var myOb = context.ExecuteStoreQuery<PlainOldClrObject>(
@"select *
from db1.dbo.table1 t1
join db2.dbo.table2 t2
on t2.t1_id = t1.id
where t1.id = {0}",
table1Id).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
您必须PlainOldClrObject使用getters/setter 定义一个类作为属性的类,例如:
class PlainOldClrObject
{
public int Id ( get; set; }
public int Name ( get; set; }
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11976 次 |
| 最近记录: |