我有以下实体(I18N是本地化实体):
public class Post {
public Int32 Id { get; set; }
public Boolean IsPublished { get; set; }
public Category Category { get; set; }
public List<PostI18N> PostsI18N { get; set; }
}
public class Category {
public Int32 Id { get; set; }
public List<CategoryI18N> CategoriesI18N { get; set; }
}
public class PostI18N {
public Int32 Id { get; set; }
public String LanguageCode { get; set; }
public String Text { get; set; }
public String Title { get; set; }
}
public class CategoryI18N {
public Int32 Id { get; set; }
public String LanguageCode { get; set; }
public String Name { get; set; }
public String Slug { get; set; }
}
我需要获得一个帖子列表,其中的类别都已本地化,所以我有:
var posts = await _context
.Posts
.SelectMany(x => x.PostsI18N,
(Post, PostI18N) => new { Post, PostI18N, Post.Category })
.Where(x => x.PostI18N.LanguageCode == "en")
.Select(x => new PostDTO {
Id = x.Post.Id,
Title = x.PostI18N.Title,
Text = x.PostI18N.Text,
CategoryDto = new CategoryDto {
Id = x.Category.Id,
Name = // ??
Slug = // ??
// The name and slug should be taken from
// x.Post.Category.CategoriesI18N which has LanguageCode = "en"
}
});
我的问题是如何获取类别本地化信息(请参阅查询中的评论)。
有谁知道怎么做?
答案 0 :(得分:0)
这听起来像你想要的
Name = x.Post.Category.CategoriesI18N.Any(c => c.LanguageCode == "en")
? x.Post.Category.CategoriesI18N.First(c => c.LanguageCode == "en").Name
: string.Empty // or whatever default you want when a match is not found
或者它可能更有意义
CategoryDto = x.Post.Category.CategoriesI18N
.Where(c => c.LanguageCode == "en")
.Select(c => new CategoryDto {
Id = x.Category.Id,
Name = c.Name,
Slug = c.Slug
}).FirstOrDefault()
如果所有值都来自同一个CategoryI18N
如果您仍然需要CategoryDto
,如果没有匹配项,您只需在?? new CategoryDto { ... }
之后添加FirstOrDefault()
。