JoRouss
JoRouss

Reputation: 2884

Entity many to many check if relation exists

I have two tables: Items and Colors. They have a many to many relation. In a CheckBoxList that displays colors, I want to check those that are associated to the item shown.

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;
    }
}

This works fine, but I was wondering about this line :

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

Is there any better way to check if the association exist?

Thank you!

EDIT

I chaged my code to something better.. I think. Is there still a better way to do this?

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;
     }
}

Many thanks!

Code update

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);
    }
}

Upvotes: 0

Views: 2158

Answers (1)

user1228750
user1228750

Reputation: 26

The line could at least be rewritten as :

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

Upvotes: 1

Related Questions