Can code-first Entity Framework do cross database queries with SQL Server DBs on the same box?

后端 未结 4 1893
终归单人心
终归单人心 2020-12-31 09:06

I know there have been a lot of questions about Entity Framework doing cross database queries on the same server posted to stackoverflow. Mostly the answer seems to be \'no\

4条回答
  •  一向
    一向 (楼主)
    2020-12-31 09:53

    Warning! using DefiningQuerys can be VERY SLOW!

    Here's an example:

    If this is the defining query that you create an Entity against:

    Select
        C.CustomerID,
        C.FirstName,
        C.LastName,
        G.SalesCatetory
    From
        CustomerDatabase.dbo.Customers C
        Inner Join MarketingDatabase.dbo.CustomerCategories G on G.CustomerID = C.CustomerID
    

    Then when you do a select against the Entity by CustomerID, the SQL trace looks something like this:

    Select
    [Extent1].[CustomerID] as [CustomerID],
    [Extent1].[FirstName] as [FirstName],
    [Extent1].[LastName] as [LastName],
    [Extent1].[SalesCatetory] as [SalesCatetory]
    From (
            Select
                C.CustomerID,
                C.FirstName,
                C.LastName,
                G.SalesCatetory
            From
                CustomerDatabase.dbo.Customers C
                Inner Join MarketingDatabase.dbo.CustomerCategories G on G.CustomerID = C.CustomerID
            ) as [Extent1]
    Where '123456' = [Extent1].[CustomerID]
    

    SQL Server may run this query very slowly. I had one case, a little more complicated than the above example, where I tried the DefiningQuery text directly in a SQl Server Management Console query window by adding a where clause for the value I wanted to select for. It run in less than a second. Then I captured the SQL Trace from selecting for the same value from the Entity created for this DefiningQuery and ran the SQL Trace query in a SQL Server query window - it took 13 seconds!

    So I guess that only real way to do cross database queries is to create a veiw on the server.

提交回复
热议问题