0

So I have an MVC application that uses OData for requests to get the right data from the database using Entity Framework Core. Mapping and everything is set. The entities look like this:

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; }
}

My call against it looks something like this:

http://localhost:8080/User(1)?$expand=UserGroups($expand=Group)

So far so good. But what I get back is the User entity, a list of UserGroup entities and their underlying Group entities:

Current Result:

{
    "UserId": 1,
    "Name": "TestUser",
    "UserGroups": [
        {
            "UserId": 1,
            "GroupId": 45,
            "Group": {
                "GroupId": 45,
                "Name": "Section1Reader"
            }
        },
        {
            "UserId": 1,
            "GroupId": 47,
            "Group": {
                "GroupId": 47,
                "Name": "Section2Writer"
            }
        }
    ]
}

I would like to not get the UserGroup entities, but the Group entities directly:

Required Result:

{
    "UserId": 1,
    "Name": "TestUser",
    "UserGroups": [
        {
            "GroupId": 45,
            "Name": "Section1Reader"
        },
        {
            "GroupId": 47,
            "Name": "Section2Writer"
        }
    ]
}
Martin Schneider
  • 14,263
  • 7
  • 55
  • 58
Evo_Kaer
  • 1
  • 1

1 Answers1

1

try doing this:

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; }
}

for more advance approch see this code https://dotnetfiddle.net/WZpeWt which posted in this answer https://stackoverflow.com/a/37376089/9673980

  • Unfortunately that won't work, since MS-SQL does not support referencing whole table entries without a foreign key. That foreign key has to exist somewhere. – Evo_Kaer Sep 26 '19 at 08:20
  • I already tried a JsonConverter. Unfortunately OData seems to just ignore those – Evo_Kaer Sep 26 '19 at 09:04