C# 试图在响应中隐藏属性,但仍获取该属性的子属性

C# 试图在响应中隐藏属性,但仍获取该属性的子属性,c#,asp.net-core,asp.net-core-mvc,entity-framework-core,odata,C#,Asp.net Core,Asp.net Core Mvc,Entity Framework Core,Odata,因此,我有一个MVC应用程序,它使用OData请求使用Entity Framework Core从数据库中获取正确的数据。映射和所有设置。实体如下所示: public class User { public long Id { get; set; } public string Name { get; set; } public ICollection<UserGroup> UserGroups { get; set; } } public class Gr

因此,我有一个MVC应用程序,它使用OData请求使用Entity Framework Core从数据库中获取正确的数据。映射和所有设置。实体如下所示:

public class User
{
    public long Id { get; set; }
    public string Name { get; set; }
    public ICollection<UserGroup> UserGroups { get; set; }
}

public class Group
{
    public long Id { get; set; }
    public string Name { get; set; }
    public ICollection<UserGroup> UserGroups { get; set; }
}

public class UserGroup
{
    public long UserId{ get; set; }
    public User User { get; set; }
    public long GroupId{ get; set; }
    public Group Group { get; set; }
}
我不想获取UserGroup实体,而是直接获取Group实体:

所需结果:

{
    "UserId": 1,
    "Name": "TestUser",
    "UserGroups": [
        {
            "UserId": 1,
            "GroupId": 45,
            "Group": {
                "GroupId": 45,
                "Name": "Section1Reader"
            }
        },
        {
            "UserId": 1,
            "GroupId": 47,
            "Group": {
                "GroupId": 47,
                "Name": "Section2Writer"
            }
        }
    ]
}
{
    "UserId": 1,
    "Name": "TestUser",
    "UserGroups": [
        {
            "GroupId": 45,
            "Name": "Section1Reader"
        },
        {
            "GroupId": 47,
            "Name": "Section2Writer"
        }
    ]
}
尝试这样做:

public class User
{
    public long Id { get; set; }

    public string Name { get; set; }

    public ICollection<UserGroup> UserGroups { get; set; }
}

public class UserGroup
{    

    public long GroupId{ get; set; }

    public string Name { get; set; }
}
公共类用户
{
公共长Id{get;set;}
公共字符串名称{get;set;}
公共ICollection用户组{get;set;}
}
公共类用户组
{    
公共长GroupId{get;set;}
公共字符串名称{get;set;}
}

有关更多高级方法,请参阅此答案中发布的代码更改对象结构?不幸的是,这行不通,因为MS-SQL不支持在没有外键的情况下引用整个表项。外键必须存在于某个地方。我已经尝试了JsonConverter。不幸的是,奥达塔似乎忽略了这些