Get a comma separated list of entity collection using linq

12,634

Solution 1

var r = _rs.Lines.Where(y => y.InvoiceNo == o.InvoiceNo).ToList().Select(x => new
{
    ReturnNo = x.Return.ReturnNo,
    Part = x.Part,
    Tags = String.Join(", ", x.Tags.Select(t => t.Name))
});

Solution 2

You can't do the concatenation in SQL, so you have to get back the data you need and then work in normal code:

var o = dgvLines.CurrentRow.DataBoundItem as Order;

var r = _rs.Lines
  .Where(y => y.InvoiceNo == o.InvoiceNo)
  .Select(x => new
    {
      ReturnNo = x.Return.ReturnNo,
      Part = x.Part,
      TagNames = x.Tags.Select( t => t.Name ),
    }
  )
  .ToList() // this runs the SQL on the database
  .Select( x => new
    {
      ReturnNo = x.ReturnNo,
      Part = x.Part,
      Tags = String.Join( ", ", x.TagNames ),
    }
  )
  .ToList();

  dgvExistingParts.DataSource = r;
Share:
12,634
sprocket12
Author by

sprocket12

Updated on June 05, 2022

Comments

  • sprocket12
    sprocket12 almost 2 years

    I have 2 entities Line and Tag. The relation is Line *----* Tag

    From line I have a navigation property Line.Tags which returns a list of Tag objects. The Tag.Name is the string value im after.

    What I really need is to get all the tag names in a comma seperated way like so :

    tag1, tag2, tag3
    

    I tried to do this in a projection, but it said it doesnt support toString()

    var o = dgvLines.CurrentRow.DataBoundItem as Order;
                    var r = _rs.Lines.Where(y => y.InvoiceNo == o.InvoiceNo).Select(x => new
                    {
                        ReturnNo = x.Return.ReturnNo,
                        Part = x.Part,
                        Tags = String.Join(", ", x.Tags.ToList().Select(t => t.Name))
                    });
                    dgvExistingParts.DataSource = r;
    

    Error:

    LINQ to Entities does not recognize the method 'System.String Join(System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.

    Any idea how I can get this comma separated list of tags?

    Thanks in advance.