简体   繁体   English

如何在 .NET EF Code First 中加入属于与另一个实体一样多的关系的实体的列或属性

[英]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.我正在开发一个 ASP.NET MVC 项目。 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如果是这样,那么您可以执行此处显示的操作: Converting a generic list to a CSV string

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在EF 4.1 Code First中将分离的实体添加到1-many关系中 - Adding detached entities to a 1-many relationship in EF 4.1 Code First 实体框架代码首先与现有实体进行多对多关系 - Entity Framework Code First Many to Many Relationship with Existing Entities EF Code首先,不是第二实体的ID单向多对多关系 - EF Code first, unidirectional many to many relationship not by Id of second entity EF4代码首先与外部实体有多对多的关系 - EF4 code first many to many relationship to external entity 首先连接EF代码多对多关系表 - Join EF code first many to many relationship tables 如何使3个实体之间的一对多关系与Entity Framework Core 2.1一起使用 - 代码优先 - How to make one-to-many relationship between 3 entities work with Entity Framework Core 2.1 - code-first 如何首先使用EF代码编写Linq查询多对多关系 - how to write a Linq query with a EF code first Many to Many relationship EF代码中的多对多关系表示 - Many to Many Relationship Representation in EF Code First 与EF 6代码中的额外列有多对多关系? - Many to Many Relationship with extra columns in EF 6 Code? 如何在EF 6中更新外键-代码优先-一对多关系 - How to update foreign key in EF 6 - Code First - One to many relationship
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM