EF Core和ASP.NET Core 7:在结果输出中去除导航字段

huangapple go评论55阅读模式
英文:

EF Core & ASP.NET Core 7 : get rid of a navigation field at result output

问题

我正在使用Entity Framework Core开发一个ASP.NET Core 7 Web API。有两个类(PostTag),它们之间有导航属性,还有一个没有导航属性的关联类(PostTag)。

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:

Post class

Tag class

PostTag class

Also there's the query that selects posts with tags

Query

And the result output:

Result

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();

EF Core和ASP.NET Core 7:在结果输出中去除导航字段

英文:

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&lt;Post&gt; 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=&gt;x.tags).ToListAsync();

to select Post include Tag, It will ignore navigation field in Tag.

EF Core和ASP.NET Core 7:在结果输出中去除导航字段

huangapple
  • 本文由 发表于 2023年8月9日 01:48:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定