I have two entities:
public class Asset
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Type")]
public short TypeId { get; set; }
public AssetType Type { get; set; }
}
public class AssetType
{
public short Id { get; set; }
public string Name { get; set; }
public ICollection<Asset> Assets { get; set; }
}
And my DbContext:
public class ApplicationDbContext : DbContext
{
public DbSet<Asset> Assets { get; set; }
public DbSet<AssetAccess> AssetAccesses { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{ }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{ }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<AssetType>().HasIndex(entity => entity.Name).IsUnique();
}
}
When I try to select Assets
from database like this:
var assets = _dbContext.Assets
.Include(asset => asset.Type)
.ToList();
I receive the list of Asset
with theirs Types
but in Type
object there are list of associated Asset
objects so it repeats endlessly.
[
{
"id": 12,
"name": "asset",
"type": {
"id": 1,
"name": "type",
"assets": [
{
"id": 12,
"name": "asset",
"type": {
... and so on ...
}
},
{
"id": 13,
"name": "asset",
"type": {
... and so on ...
}
}
]
},
},
...
]
I just wanna receive list of Asset
with inner Type
that's all. So how can I get rid of this cycling?
In startup I define this:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(option => option.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
But it doesn't work.