【发布时间】:2019-12-08 16:59:09
【问题描述】:
我有两个实体:
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 ...
}
}
]
},
},
...
]
我只想接收带有内部Type 的Asset 列表,仅此而已。那么我怎样才能摆脱这种循环呢?
在启动时我定义了这个:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(option => option.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
但它不起作用。
【问题讨论】:
-
你应该返回视图模型而不是你的实体。
-
@CodeNotFound ,是的,我这样做了。但我使用 AutoMapper 将我的域模型转换为视图模型。当域模型具有循环引用时,AutoMapper 返回更多对象,那么它必须而且我不想返回额外的无用数据
-
@Artyom DTO/视图模型的整个想法是它们不应该有循环引用——你只创建你需要的属性。 EF(存储)实体模型中的循环引用没有问题 - EF 正在正确处理它们,而 AM(尤其是投影)也可以做到这一点。
-
你当前的 ViewModel 是什么?
标签: linq asp.net-core entity-framework-core