简体   繁体   中英

How to join columns or properties of entities that belongs as many relationship to another entity in .NET EF Code First

I am developing a ASP.NET MVC project. In my project, I am using Entity Framework code first approach. But I am having a problem with that.

This is item class

class Item{
  public int Id { get; set; }
  .
  .
  .
  public virtual ICollection<Category> Categories { get; set; }
}

This is category class

public class Category{
   public int Id{ get; set; }
   public int Name { get; set; }

   public virtual ICollection<Item> Items { get; set; }
}

As you can see above they are in many-to-many relationship. What I want to do is as below.

var item = db.find(2); //I retrieve a single item
var item.Categories; // this is how I get all categories of that item
item.Categories.Select(x=>x.Name).Join(?); // I want to retrieve all category names of that item as CSV value.

How can I achieve this?

Since you already for all the categories for this item, I am assuming you are looking for how to convert a list of string to comma separated string. Is that right? If so, then you can do what is shown here: Converting a generic list to a CSV string

    IEnumerable<T> myList;
string csv = String.Join(",", myList.Select(x => x.ToString()).ToArray());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM