连接EF实体嵌套列表标题

时间:2013-10-11 02:20:44

标签: c# linq entity-framework string-concatenation

我有非常简单的实体。

我的Article实体:

public class Article
{
    public Article()
    {
        Tags = new HashSet<Tag>();
    }

    public Guid Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }

    public virtual ICollection<Tag> Tags { get; set; }
}

Tag实体:

public class Tag
{
    public Guid Id { get; set; }
    public string Title { get; set; }
}

这些实体之间的关系(多对多)

modelBuilder.Entity<Article>()
    .HasMany(a => a.Tags)
    .WithMany()
    .Map(m =>
    {
        m.MapLeftKey("ArticleId");
        m.MapRightKey("TagId");
        m.ToTable("ArticlesTags");
    });

问题

我想显示带有用空格分隔的标签的文章表。

我的查询不起作用:

var articles = from article in dbContext.KBArticles
               select new ArticlesListModel()
               {
                   Id = article.Id,
                   Title = article.Title,
                   Tags = string.Join(" ", article.Tags.Select(t => t.Title).ToArray<string>())
               };

网络服务器显示错误LINQ to Entities does not recognize the method "System.String Join(System.String, System.String[])" method, and this method cannot be translated into a store expression"

1 个答案:

答案 0 :(得分:1)

您可以使用AsEnumerableToList并首先从数据库中检索数据,然后对其进行处理。

var articles = from article in dbContext.KBArticles.AsEnumerable()
               select new ArticlesListModel()
               {
                   Id = article.Id,
                   Title = article.Title,
                   Tags = string.Join(" ", article.Tags.Select(t => t.Title).ToArray<string>())
               };