Using linq, get a comma-separated list of entity collections.

c# entity-framework linq

Question

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.

1
1
5/3/2012 2:07:08 PM

Accepted Answer

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))
});
7
5/3/2012 2:11:57 PM

Popular Answer

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;


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow