【问题标题】:Dynamic Queries: Change table name in LINQ-to-Entities query动态查询:在 LINQ-to-Entities 查询中更改表名
【发布时间】:2013-05-02 01:04:49
【问题描述】:

潜伏已久,新人。

在使用 LINQ-to-Entities 进行查询时遇到了一些困难。我正在为 Web 和实体框架 4.0 使用 Visual Studio Express 2012。请耐心等待,这是一个很长的解释,以确保我涵盖了所有内容。情况如下:

我有一个可重复使用的 .aspx 页面,它充当图像管理器。它有一个Ajax Toolkit FileUpload 控件和一个Repeater 来显示上传的文件。我在 Fancybox 模态弹出窗口 (iframe) 中访问此管理器。它的打开 URL 有 2 个参数,一个“ID”和一个“Type”。

在我的 ImageManager 代码隐藏文件中,我有一个将所有图像绑定到中继器的函数。在这个函数中,我需要根据“类型”(url参数)查询一个数据库表......这正是问题所在。

对于我的生活,我不知道如何编写一个动态 LINQ-to-Entities 查询,其中表名将更改,根据类型更改...

这是函数(有问题的部分有cmets):

private void BindImagesRepeater()
{
    DatabaseEntities db = new DatabaseEntities();
    FolderName = Session["foldername"].ToString();
    FolderPath = Server.MapPath("~") + "controls/" + FolderName + "/images";
    int itemid = Convert.ToInt32(Session["itemID"]);
    bool dirExist = Directory.Exists(@FolderPath + "/" + itemid);
    bool isSpotlight = false;
    string spotlightThumbPath = "";
    string thumbPath = "";
    string thumbname = "";
    string spotlightName = "";
    int thumbPosition = 0;
    int spotlightPosition = 0;
    int counter = 0;
    int rptrCount = 0;

    /////PART I DON'T QUITE UNDERSTAND
    var query = null; //I know this is impossible

    //select the Table to query
    switch (FolderName)
    {
        case "NewsManager":
            query = (from q in db.News Where q.ID == itemID select q);
            break;
        case "ProductsManager":
            query = (from q in db.Products Where ...
            break;
        case "ProjectsManager":
            query = ... db.Projects ...
            break;
        case "CalendarManager":
            query = ... db.Events ...
            break;
    }
    /////


    if (query.Count > 0)
    {
        var uniqueItm = query.First();

        isSpotlight = Convert.ToBoolean(uniqueItm.isSpotlight);
        thumbPath = uniqueItm.thumbnailPath;
        spotlightThumbPath = uniqueItm.spotlightThumbPath;

        thumbname = Path.GetFileNameWithoutExtension(thumbPath);
        spotlightName = Path.GetFileNameWithoutExtension(spotlightThumbPath);

        if (dirExist)
        {
            if (!String.IsNullOrWhiteSpace(FolderPath))
            {
                List<string> fileNames = GetFiles(FolderPath + "/" + itemid, "*.bmp|*.gif|*.jpg|*.jpeg|*.png", SearchOption.TopDirectoryOnly);
                var files = (from f in fileNames
                             where (!f.Contains("_Thumb")) && (!f.Contains("_SpotlightThumb"))
                             select new
                             {
                                 FilePath = f,
                                 FileName = System.IO.Path.GetFileName(f)
                             });

                if (files.Count() > 0)
                {
                    imagesRepeater.DataSource = files;
                    imagesRepeater.DataBind();

                    foreach (var img in files)
                    {

                        if (thumbPath != "" && thumbPath != null)
                        {
                            if (img.FileName.Contains(thumbname.Replace("_Thumb", "")))
                            {
                                thumbPosition = counter;
                            }
                        }

                        if (spotlightThumbPath != "" && spotlightThumbPath != null)
                        {
                            if (img.FileName.Contains(spotlightName.Replace("_SpotlightThumb", "")))
                            {
                                spotlightPosition = counter;
                            }
                        }

                        counter++;
                    }

                    if (isSpotlight)
                    {
                        foreach (RepeaterItem item in imagesRepeater.Items)
                        {
                            LinkButton spotlightLnkBtn = (LinkButton)item.FindControl("useAsThumbnailSpotlight");
                            spotlightLnkBtn.Visible = true;

                            if (thumbPath != "" && thumbPath != null)
                            {
                                if (rptrCount == thumbPosition)
                                {
                                    Label myThumbImage = (Label)item.FindControl("lblThumb");
                                    myThumbImage.Visible = true;
                                }
                            }

                            if (spotlightThumbPath != "" && spotlightThumbPath != null)
                            {
                                if (rptrCount == spotlightPosition)
                                {
                                    Label mySpotlightImage = (Label)item.FindControl("lblThumbSpotlight");
                                    mySpotlightImage.Visible = true;
                                }
                            }

                            rptrCount++;
                        }
                    }
                    else
                    {
                        foreach (RepeaterItem item in imagesRepeater.Items)
                        {
                            if (thumbPath != "" && thumbPath != null)
                            {
                                if (rptrCount == thumbPosition)
                                {
                                    Label myThumbImage = (Label)item.FindControl("lblThumb");
                                    myThumbImage.Visible = true;
                                }
                            }

                            if (spotlightThumbPath != "" && spotlightThumbPath != null)
                            {
                                if (rptrCount == spotlightPosition)
                                {
                                    Label mySpotlightImage = (Label)item.FindControl("lblThumbSpotlight");
                                    mySpotlightImage.Visible = true;
                                }
                            }

                            rptrCount++;
                        }
                    }

                    uniqueItm.hasImages = true;
                    db.SaveChanges();
                    lblEmptyData.Visible = false;
                }
                else
                {
                    uniqueItm.hasImages = false;
                    db.SaveChanges();
                    lblEmptyData.Visible = true;
                }
            }
        }
    }
    else
    {
        lblEmptyData.Visible = true;
    }
}

我尝试了一些不同的方法,但都无济于事。我有点难过。 如果我可以将我的“var 查询”设为 NULL,那将解决它,但是,当然,这是不可能的,因为这个变量是隐式类型的。

除了使用“var”之外,必须有一种方法来声明我的变量...

如果有人有任何想法,我将不胜感激。我希望我足够简洁。

提前致谢

【问题讨论】:

    标签: c# .net sql entity-framework linq-to-entities


    【解决方案1】:

    通过查看您如何使用查询,您的结果似乎是强类型的 ...

       var uniqueItm = query.First();
    
        isSpotlight = Convert.ToBoolean(uniqueItm.isSpotlight);
        thumbPath = uniqueItm.thumbnailPath;
        spotlightThumbPath = uniqueItm.spotlightThumbPath;
    

    每个查询都应返回具有 isSpotlight、thumbnailPath、spotlightThumbPath 属性的结果。 那么为什么不为此创建类:

    public class MyQueryResult
    {
      public bool isSpotlight{get;set;}
      public string thumbPath{get;set;}
      public string spotlightThumbPat{get;set;}
    }
    

    然后键入所有查询以返回 MyQueryResult 的对象

    IQueryable<MyQueryResult> query = null; //This is now possible
    //select the Table to query
    switch (FolderName)
    {
        case "NewsManager":
            query = from q in db.News Where q.ID == itemID 
                     select new MyQueryResult
                     {
                         isSpotLight=q.Something,
                         thumbPath = q.SomethingElse
                         etc...
                      }
            break;
        case "ProductsManager":
            query = (from q in db.Products Where ...
                     select new MyQueryResult
                     {
                         ---fill properties
                     }
            break;
         .... same thing for every case
      }
    
      var uniqueItm = query.FirstOrDefault();
      if (uniqueItm!=null)
      {
          ... do your thing with uniqueItm
      } 
    

    【讨论】:

    • 天哪,我什至不知道这是可能的……这确实成功了。 :) 太感谢了!!我想我只是升级了一些
    【解决方案2】:

    实际上,我可能有一个解决方案:

    注意:该解决方案未经测试。

    第一:

    在你的情况下,var result,正如你所说,是隐式输入的。但实际上它相当于IEnumerable&lt;object&gt; result。您可以改用IEnumerable&lt;object&gt; result = nullIEnumerable&lt;object­&gt;? result 来接受可为空的值。

    第二:

    第二种解决方案包括将查询部分移动到自己的方法中,接受字符串参数,返回对象集合或可为空的IEnumerable&lt;T&gt;? 集合。

    问候!

    【讨论】:

    • 另一个解决方案解决了我的问题,但您的解决方案也很有意义。我会记住这一点,以备后用。感谢您花时间寻找解决方案。
    猜你喜欢
    • 2012-10-25
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多