实体框架核心对象循环

时间:2019-07-31 08:20:50

标签: linq asp.net-core entity-framework-core

我有两个实体:

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

还有我的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();
        }
    }

当我尝试从数据库中选择Assets时,

var assets = _dbContext.Assets
    .Include(asset => asset.Type)
    .ToList();

我收到了Asset及其Types的列表,但是在Type对象中有关联的Asset对象的列表,因此它会不断重复。

[
    {
        "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 ...
                    }
                }
            ]
        },
    },
    ...
]

我只想接收带有内部Asset的{​​{1}}列表。那么,如何摆脱这种骑车运动呢? 在启动时,我定义如下:

Type

但这不起作用。

2 个答案:

答案 0 :(得分:0)

您可以尝试向Type和Assets属性添加虚拟关键字吗?这应该使它们可以被延迟加载,因此您不应该获得循环引用?

您可以在此处了解更多信息:navigation property should be virtual - not required in ef core

您也可以尝试添加此设置:

services.AddMvc().AddJsonOptions(options => {
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        });

答案 1 :(得分:0)

要返回没有附加循环对象的ViewModel,请尝试按照以下步骤操作:

  1. ViewModel

    public class AssetVM
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public AssetTypeVM Type { get; set; }
    }
    
    public class AssetTypeVM
    {
        public short Id { get; set; }
        public string Name { get; set; }
    }
    
  2. 个人资料

    public class ModelProfile: Profile
    {
        public ModelProfile()
        {
            CreateMap<AssetType, AssetTypeVM>();
            CreateMap<Asset, AssetVM>();
        }
    }
    
  3. 使用

    var assets = _context.Assets
                .Include(asset => asset.Type)
                .ToList();
    var assetsVM = _mapper.Map<List<AssetVM>>(assets);