I have the following classes (annotated for brevity);
public partial class Device
{
[Key]
public int ID { get; set; }
public virtual Policy MainPolicy { get; set; }
}
public class Policy
{
[Key]
public override int ID { get; set; }
[ForeignKey("ID"), Column("deviceid")]
public virtual Device MainDevice { get; set; }
}
Now when I try to select from the db using linq (for example from device perspective and try to include policy data).
When I then try to return the serialized result I am getting a Self referencing loop detected for the property device and policy.
For example, selecting from the devices perspective;
var result = _dbset
.Include(x => x.Policy)
.Where(predicate);
return result.ToList();
I then go to look to filter and return the results in my webapi method as follows;
var filtered = from x in results
select new
{
ID = x.ID,
PolicyNumber = x.MainPolicy.Number,
Created = x.CreatedDate
};
return Ok(filtered);
As far as I was aware the ForeignKey attribute should fix this? i.e. in the above code by decorating the MainDevice with the ForeignKey("ID") this should tell EF which way around the relationship is?
I'd rather fix and understand this than simply adding the json ignore loop if possible.
jsonhas to do with anything.ForeignKeyor any of the entity framework configuration.