DbContext-FromSql无法替换数据库名称

时间:2017-08-16 15:42:48

标签: sql asp.net-core .net-core dbcontext entity-framework-core

我正在使用我的.NET Core应用程序来查询某些数据。在我的应用程序中,我使用两种不同的上下文。由于LINQ / EF无法在两个上下文之间加入,我正在使用DbContext..FromSql进行查询:

IQueryable<Articles> query = _contextA.Articles.FromSql<Articles>(
    @"SELECT    a.*, ra.Barcode AS RequestedBarcode
    FROM        dbo.Articles a
    INNER JOIN  Webservice.dbo.RequestArticle ra
            ON  ra.ProducerId = a.ProducerId AND ra.Barcode = a.Barcode
    WHERE       ra.RequestId = {0}",
    ArticleRequestGuid);

此查询的功能类似于魅力。现在我想从我的其他上下文中动态替换我的“Webservice”-database-name。

IQueryable<Articles> query = _contextA.Articles.FromSql<Articles>(
    @"SELECT    a.*, ra.Barcode AS RequestedBarcode
    FROM        dbo.Articles a
    INNER JOIN  {1}.dbo.RequestArticle ra
            ON  ra.ProducerId = a.ProducerId AND ra.Barcode = a.Barcode
    WHERE       ra.RequestId = {0}",
    ArticleRequestGuid,
    _contextB.Database.GetDbConnection().Database);

_contextB.Database.GetDbConnection()。数据库中的值是完全正确的值字符串。但查询仍然失败,并显示以下错误消息:

"message": "Falsche Syntax in der Nähe von '.'.",
"detail": "
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__107_0(Task`1 result)\r\n
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()\r\n
at System.Threading.Tasks.Task.Execute()\r\n
--- End of stack trace from previous location where exception was thrown ---\r\n

“Nähevon中的Falsche语法'。'。”意思是“错误的语法接近'。'。”

做错了什么?

更新: 之前的例子是使用Core 1.1完成的。现在我已更新到Core 2.0。

这很好用:

IQueryable<Articles> query = _contextA.Articles.FromSql<Articles>(
@"SELECT    a.*, ra.Barcode AS RequestedBarcode
FROM        dbo.Articles a
INNER JOIN  Webservice.dbo.RequestArticle ra
        ON  ra.ProducerId = a.ProducerId AND ra.Barcode = a.Barcode
WHERE       ra.RequestId = {ArticleRequestGuid}");

这不起作用:

string webserviceDatabaseName = "Webservice";
IQueryable<Articles> query = _contextA.Articles.FromSql<Articles>(
@"SELECT    a.*, ra.Barcode AS RequestedBarcode
FROM        dbo.Articles a
INNER JOIN  {webserviceDatabaseName}.dbo.RequestArticle ra
        ON  ra.ProducerId = a.ProducerId AND ra.Barcode = a.Barcode
WHERE       ra.RequestId = {ArticleRequestGuid}");

似乎这样不起作用。

1 个答案:

答案 0 :(得分:1)

由于问题是开放一段时间,我在SQL语句中直接使用“String.Format”而不是Variable-names:

string sqlQuery = String.Format(
    @"SELECT    a.*, ra.Barcode AS RequestedBarcode
      FROM        dbo.Articles a
      INNER JOIN  {0}.dbo.RequestArticle ra
        ON  ra.ProducerId = a.ProducerId AND ra.Barcode = a.Barcode
      WHERE       ra.RequestId = '{1}'",
    _contextB.Database.GetDbConnection().Database,
    ArticleRequestGuid
    );
var query = _contextA.Articles.FromSql<Articles>(sqlQuery);

不知何故,第一个变种根本不起作用。似乎不值得为此问题投入更多精力。