真相大白:為什麼Entity Framework不能進行跨資料庫查詢(附解決方案)

來源:互聯網
上載者:User

在上篇隨筆中,我們發現Entity Framework在構建SQL語句時,將ToTable("CNBlogsTex.dbo.blog_PostBody")中的"CNBlogsTex.dbo.blog_PostBody"轉換為"[CNBlogsText.dbo].[blog_PostBody]",從而造成不能進行跨資料庫查詢。

今天上午,我們通過Reflector對Entity Framework的代碼進行分析,找出了真相。

真相如下:

1. 對於“CNBlogsTex.dbo.blog_PostBody"字串,Entity Framework對其進行了拆分,拆分為:Schema名稱(CNBlogsTex.dbo)與資料庫表名稱(blog_PostBod)。

這部分是在System.Data.Entity.ModelConfiguration.Utilities.ObjectExtensions的ParseQualifiedTableName()方法中處理的,Reflector出來的代碼如下:

public static void ParseQualifiedTableName(string qualifiedName, out string schemaName, out string tableName)
{
qualifiedName = qualifiedName.Trim();
int length = qualifiedName.LastIndexOf('.');
schemaName = null;
tableName = qualifiedName;
switch (length)
{
case -1:
break;

case 0:
throw Error.ToTable_InvalidSchemaName(qualifiedName);

default:
if (length == (tableName.Length - 1))
{
throw Error.ToTable_InvalidTableName(qualifiedName);
}
schemaName = qualifiedName.Substring(0, length);
tableName = qualifiedName.Substring(length + 1);
break;
}
if (string.IsNullOrWhiteSpace(schemaName))
{
schemaName = null;
}
}

2. 方括弧的添加(CNBlogsTex.dbo變為[CNBlogsTex.dbo],blog_PostBod變為[blog_PostBod])是在System.Data.SqlClient.SqlDdlBuilder的AppendIdentifier(string identifier)方法中處理的,Reflector出來的代碼如下:

private void AppendIdentifier(string identifier)
{
this.AppendSql("[" + identifier.Replace("]", "]]") + "]");
}

所以,當我們當表名改為"CNBlogsText].[dbo.blog_PostBody"時,"CNBlogsText].[dbo"就被轉換為"[CNBlogsText]].[dbo]"。

不僅有代碼有真相,而且有圖有真相:

知道了真相,目前只能望真相心歎,能不能解決這個問題還是未知數...

更新:

killkill的一句回複讓“心歎”變成了“興奮”,那種程式員特有的,一般人享受不到的興奮...

原來要欺騙的不是Entity Framework,而且是SQL Server,用SQL Server的同義字(SYNONYM)可以輕鬆搞定這個問題,建立同義字的SQL語句如下:

CREATE SYNONYM [dbo].[CNBlogsText__blog_PostBody] FOR [CNBlogsText].[dbo].[blog_PostBody]

非常感謝killkill的協助!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.