实体多对多检查是否存在关系

时间:2012-02-29 13:09:53

标签: c# entity-framework-4

我有两个表:项目和颜色。他们有很多关系。在显示颜色的CheckBoxList中,我想检查与显示的项目相关联的那些。

using (var db = new ProwebModel.Entities())
{
    var colors = db.Colors;

    foreach (ListItem color in ((CheckBoxList)(fv.FindControl("cblColors"))).Items)
    {
        var itemId = Convert.ToInt32(Request.QueryString["id"]);
        var colorNumber = Convert.ToInt32(color.Value);
        color.Selected = colors.Where(t => t.ColorNumber == colorNumber).First().Items.Where(t => t.ItemId == itemId).Count() > 0;
    }
}

这很好用,但我想知道这一行:

color.Selected = colors.Where(t => t.ColorNumber == colorNumber).First().Items.Where(t => t.ItemId == itemId).Count() > 0;

有没有更好的方法来检查关联是否存在?

谢谢!

修改

我把我的代码改成了更好的东西......我想。还有更好的方法吗?

using (var db = new ProwebModel.Entities())
{
     var itemId = Convert.ToInt32(Request.QueryString["id"]);
     var ItemColors = db.Items.First(t => t.ItemId == itemId).Colors.ToList();

     foreach (ListItem color in ((CheckBoxList)(fv.FindControl("cblColors"))).Items)
     {
          var colorNumber = Convert.ToInt32(color.Value);
          color.Selected = ItemColors.Where(t => t.ColorNumber == colorNumber).Count() > 0;
     }
}

非常感谢!

代码更新

using (var db = new ProwebModel.Entities())
{
    var itemId = Convert.ToInt32(Request.QueryString["id"]);
    var ItemColors = db.Items.First(t => t.ItemId == itemId).Colors.ToList();

    foreach (ListItem color in ((CheckBoxList)(fv.FindControl("cblColors"))).Items)
    {
        var colorNumber = Convert.ToInt32(color.Value);
        color.Selected = ItemColors.Any(t => t.ColorNumber == colorNumber);
    }
}

1 个答案:

答案 0 :(得分:1)

该行至少可以改写为:

color.Selected = colors.First(t => t.ColorNumber == colorNumber).Items.Any(t => t.ItemId == itemId);