英文:
EF Core & ASP.NET Core 7 : get rid of a navigation field at result output
问题
我正在使用Entity Framework Core开发一个ASP.NET Core 7 Web API。有两个类(Post
和Tag
),它们之间有导航属性,还有一个没有导航属性的关联类(PostTag
)。
还有一个查询语句,用于选择带有标签的帖子。
查询结果如下:
如你所见,一个帖子包含一个标签列表,问题是每个标签都包含来自Tag
类导航属性的帖子。
问题是如何去掉标签中的这些帖子,我只想要Titles
,不要帖子。
提前感谢!
我尝试阅读EF Core文档并在Google上搜索答案,但没有结果。
英文:
I work on an ASP.NET Core 7 Web API using Entity Framework Core for the purpose.
There are two classes (Post, Tag
) with navigation fields and the join class (PostTag
) with no navigation fields:
Also there's the query that selects posts with tags
And the result output:
As you can see a post contains tags list and the issue is that every tags contains a post that comes from Tag
class navigation field.
The question - how do I get rid of these posts in the tag, I'd like to have Titles
only, no posts at all?
Thanks for advance!
I tried to read the EF Core documentation and google the answer, no result.
答案1
得分: 0
要么在Tag上移除帖子导航属性,要么使用Select仅选择你想要的属性。
你还可以创建只包含你想要的属性的DTO类,并将结果映射到这些对象上。当DTO类的属性与你的实体具有相同的名称时,你可以使用AutoMapper和ProjectTo扩展方法来进行映射。这将简化你的工作。
英文:
Either remove the post navigation property on Tag or use Select to only select the properties you want.
You can also create DTO classes that only include the properties that you want and map the result to those objects. When the properties of the DTO classes have the same name as your enties you could use AutoMapper to do the mapping for you with the ProjectTo extension method. This will simplify things for you.
答案2
得分: 0
你可以在Tag模型的导航字段上添加[JsonIgnore]
属性:
public class Tag
{
public int Id { get; set; }
public string Title { get; set; }
[JsonIgnore]
public List<Post> posts { get; set; } = new();
}
这个属性表示在序列化过程中检测到引用循环时是否忽略对象。
然后,当你使用以下代码选择Post
并包含Tag
时,它将忽略Tag中的导航字段:
return await _context.Post.Include(x=>x.tags).ToListAsync();
英文:
You can add [JsonIgnore]
attribute to the navigation field in Tag model:
public class Tag
{
public int Id { get; set; }
public string Title { get; set; }
[JsonIgnore]
public List<Post> posts { get; set; } = new();
}
This attribute indicates whether an object is ignored when a reference cycle is detected during serialization.
Then when you use
return await _context.Post.Include(x=>x.tags).ToListAsync();
to select Post
include Tag
, It will ignore navigation field in Tag.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论