linq - 实体框架核心对象循环
问题描述
我有两个实体:
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);
但它不起作用。
解决方案
要返回 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; } }
轮廓
public class ModelProfile: Profile { public ModelProfile() { CreateMap<AssetType, AssetTypeVM>(); CreateMap<Asset, AssetVM>(); } }
利用
var assets = _context.Assets .Include(asset => asset.Type) .ToList(); var assetsVM = _mapper.Map<List<AssetVM>>(assets);
推荐阅读
- android - 以编程方式将事件添加到日历
- json - 在使用 React Native 的某些记录后无法将值保存到 localMongoDB
- android - 如何将 android 模块用作应用程序和库
- java - How to extract the dynamic values of the id attributes of the table elements using Selenium and Java
- shopify - 关于“主题获取”命令 shopify 的问题
- gradle - 如何从 Gradle Kotlin DSL 表达式中访问项目版本?
- angular - 路由到具有不同参数的相同网址后,页面上的数据未更新
- reactjs - 如何修复反应表中的分页重置问题?
- sql - 通过调用存储过程更新表的 Null 记录会引发错误“子查询返回多个值”
- php - 如何解决这个问题“未定义的变量:类别”?