r/dotnet•
Pr1m-e

[Help] Web Api; Entity Framework; Data returns recursice

Hi,

im facing a problem with probably selfreference Looping:

Model:

 public class ProtectedAccount
{
    public int Id { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime Created { get; private set; }
    public DateTime? Changed { get; set; }
    public bool Disabled { get; set; }

    public virtual ICollection<ProtectedAccountMember> Members { get; set; }
    public virtual ProtectedAccountType Type { get; set; }
}


 public class ProtectedAccountMember
{

    public int Id { get; set; }
    [StringLength(300)]
    public string Name { get; set; }

    [Index]
    public virtual ProtectedAccount ProtectedAccount { get; set; }
}

Controller:

    [ResponseType(typeof(ProtectedAccount))]
    [Route("ProtectedAccounts/{id}/Members")]
    [HttpGet]
    public IHttpActionResult GetProtectedAccountMembers(int id)
    {
        var protectedAccount = db.ProtectedAccounts.Find(id);

        if (protectedAccount == null)
        {
            return NotFound();
        }
        
        return Ok(protectedAccount.Members.ToList());
    }

the data wich i receive for an GET seems to Loop recursive through all navigations:

[
  {
	"ProtectedAccount": {
	  "Members": [
		{
		  "Id": 2,
		  "Name": "XXX, XX",
	   
		},
		{
		  "Id": 3,
		  "Name": "XX, XX",
		 
		}
	  ],
	  "Type": null,
	  "Id": 25,
	  "ObjectGUID": "76bf65e7-af60-4fe8-b3e1-90afbfd65b65",
	  "Name": "XXX",
	 
	},
	"Id": 1,
	"Name": "test",
  },
  {
	"ProtectedAccount": {
	  "Members": [
		{
		  "Id": 1,
		  "Name": "test",
		  
		},
		{
		  "Id": 3,
		  "Name": "XX, XX",
		  "SamAccountName": "XX",
		  "Disabled": false
		}
	  ],
	  "Type": null,
	  "Id": 25,
	  "ObjectGUID": "76bf65e7-af60-4fe8-b3e1-90afbfd65b65",
	  "Name": "XXXX",
	  
	},
	"Id": 2,
	"Name": "XX, XX",

  },
  {
	"ProtectedAccount": {a
	  "Members": [
		{
		  "Id": 1,
		  "Name": "test",
		  "SamAccountName": "XXX",
		  "Disabled": false
		},
		{
		  "Id": 2,
		  "Name": "XX, XX",
		  "SamAccountName": "XX",
		  "Disabled": false
		}
	  ],
	  "Type": null,
	  "Id": 25,
	  "ObjectGUID": "76bf65e7-af60-4fe8-b3e1-90afbfd65b65",
	  "Name": "XXX",
	},
	"Id": 3,
	"Name": "XX, XX",

  }
]

There is only one "ProtectedAccount" in the database. DO i have to use DTO to overcome this issue? I tried some configuration via the json formatsettings but didnt get any better results.

Posted Feb 1, 2016, 3:10 PM UTC · edited

711
Loading comments…