Get a comma separated list of entity collection using linq
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;
sprocket12
Updated on June 05, 2022Comments
-
sprocket12 almost 2 years
I have 2 entities
Line
andTag
. The relation isLine *----* Tag
From
line
I have a navigation propertyLine.Tags
which returns a list of Tag objects. TheTag.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.