动态查询:在LINQ到实体查询中更改表名

时间:2013-05-07 22:49:38

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

长期潜伏,最近的新人。

使用LINQ-to-Entities进行查询时遇到了一些困难。我正在使用Visual Studio Express 2012 for Web和Entity Framework 4.0。忍受我,这是一个很长的解释,以确保我涵盖一切。情况如下:

我有一个可重复使用的.aspx页面,它充当图像管理器。它有一个Ajax Toolkit FileUpload控件和一个Repeater来显示上传的文件。我在Fancybox Modal Pop-up(iframe)中访问此Manager。它的开放URL有2个参数,一个“ID”和一个“类型”。

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

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

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

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 query”能够解决它,但是,当然,这是不可能的,因为这个变量是隐式类型的。

除了使用“var”...

之外,必须有一种声明我的变量的方法

如果有人有任何想法,我会非常感激。我希望我已经足够简明。

提前致谢

2 个答案:

答案 0 :(得分:3)

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

   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
  } 

答案 1 :(得分:0)

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

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

<强>首先

在你的情况下,正如你所说,var result是隐式输入的。但实际上它等同于IEnumerable<object> result。您可以使用IEnumerable<object> result = nullIEnumerable<object­>? result来接受可以为空的值。

<强>第二

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

问候!