【问题标题】:Entity Framework - how to join tables without LINQ and with only string?实体框架 - 如何在没有 LINQ 且只有字符串的情况下连接表?
【发布时间】:2010-09-30 15:51:58
【问题描述】:

我有一个关于实体框架的问题。如果您知道这方面的答案,请回答。我有这样的疑问:

String queryRaw =
    "SELECT " +
    "p.ProductName AS ProductName " +
    "FROM ProductEntities.Products AS p " +
    "INNER JOIN CategoryEntities.Categories AS c " + 
    "ON p.CategoryID = c.CategoryID ";

ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>(queryRaw, entityContext);

GridView1.DataSource = query;
GridView1.DataBind();

特别是我想在一个查询中加入几个表,但我不能使用 LINQ,也不能将 ObjectQuery 与映射到查询中的 DB 字段的对象一起使用。因为每个实体都是动态创建的。所以这是我不能使用的:

msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic12

msdn.microsoft.com/en-us/library/bb896339%28v=VS.90%29.aspx

问题是我可以用这样的东西代替对象吗?

query.Join ("INNER JOIN CategoryEntities.Category ON p.CategoryID = c.CategoryID ");

目的是使用ObjectQuery的Join方法,语法和Where方法一样:

msdn.microsoft.com/en-us/library/bb338811%28v=VS.90%29.aspx

谢谢,阿尔乔姆

【问题讨论】:

    标签: sql entity-framework join objectquery


    【解决方案1】:

    我现在看到的任何决定都是临时将 ObjectQuery 转换为字符串,将连接表添加为字符串,然后将其转换回 ObjectQuery:

    RoutesEntities routesModel = new RoutesEntities(entityConnection);
    String queryRaw = "SELECT " + 
                      "rs.RouteID AS RouteID, " +
                      "rs.LocaleID AS LocaleID, " + 
                      "rs.IsSystem AS IsSystem " +
                      "FROM RoutesEntities.Routes AS rs ";
    
    _queryData = new ObjectQuery<DbDataRecord>(queryRaw, routesModel);
    
    var queryJoin = _queryData.CommandText + " INNER JOIN LocalesEntities.Locales AS ls ON ls.LocaleID = rs.LocaleID ";
    _queryData = new ObjectQuery<DbDataRecord>(queryJoin, routesModel);
    

    也许有人有更一致的建议?

    【讨论】:

      【解决方案2】:

      最后我找到了一个更好的解决方案,我们可以在主查询中使用子查询。例如:

      var db = CustomEntity();
      
      ObjectQuery<Categories> query1 = db.Categories.Where("it.CategoryName='Demo'").Select ("it.CategoryID");
      var categorySQL = query1.ToTraceString().Replace("dbo", "CustomEntity"); // E-SQL need this syntax
      ObjectQuery<Products> query2 = db.Categories.Where("it.CategoryID = (" + categorySQL + ")");
      

      这里有一些例子:

      http://msdn.microsoft.com/en-us/library/bb896238.aspx

      祝你好运!

      【讨论】:

        猜你喜欢
        • 2017-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-19
        • 2018-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多