首页 > 解决方案 > 实体框架核心对象循环

问题描述

我有两个实体:

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内部列表,仅此而已Type。那么我怎样才能摆脱这种循环呢?在启动时,我定义了这个:

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .AddJsonOptions(option => option.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

但它不起作用。

标签: linqasp.net-coreentity-framework-core

解决方案


要返回 ViewModel 而不需要额外的循环对象,请尝试按照以下步骤操作:

  1. 视图模型

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

推荐阅读