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

c# entity-framework linq

Question

My two entities areLine and Tag The connection isLine *----* Tag

From line I own a navigational asset.Line.Tags yields a list of Tag object returns. TheTag.Name I'm looking for the string value.

What I actually need is a list of all the tag names separated by commas, like this:

tag1, tag2, tag3

It claimed it doesn't support when I attempted to implement this in a projection.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:

The method "System.String Join(System.String, System.Collections.Generic.IEnumerable'1[System.String])" is not supported by LINQ to Entities, thus it cannot be converted into a store expression.

Any ideas on how I might get this list of tags separated by commas?

I appreciate it.

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

Since concatenation in SQL is not possible, you must first get the data you want before continuing to write conventional 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