在我的数据库中,我有标签和帖子表。它们之间是多对多的关系。在标签实体中,我不存储标签使用次数。此属性(Quantity
)位于标记 View 模型内。
通过使用AutoMapper
,我在Tag
和TagViewModel
之间创建了一个映射。在 AfterMap
方法中,我设置了 Quantity
属性:
Mapper.Initialize(config =>
{
config.CreateMap<Tag, TagViewModel>()
.AfterMap(async (m, vm) =>
{
vm.Quantity = await tagRepository.CountById(vm.Id);
});
});
问题是,这段代码并不总是有效。有时 Quantity
设置正确,有时设置为 0,有时出现异常:
BeginExecuteReader requires an open and available Connection. The connection's current state is open.
如何解决此问题或者映射后自动设置 Quantity
值的更好解决方案是什么?
这是我的其余代码:
实体:
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<TagPost> TagPost { get; set; } = new HashSet<TagPost>();
}
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Content { get; set; }
public virtual ICollection<TagPost> TagPost { get; set; } = new HashSet<TagPost>();
}
public class TagThread
{
public int PostId { get; set; }
public Post Post { get; set; }
public int TagId { get; set; }
public Tag Tag { get; set; }
}
标签 View 模型:
public class TagViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
}
存储库:
public async Task<int> CountById(int id)
{
var quantity = await context.Tags
.SelectMany(t => t.TagPost.Where(c => c.TagId == id))
.CountAsync();
return quantity;
}
最佳答案
您的 Tag 类上有一个导航属性,那么为什么不这样做:
config.CreateMap<Tag, TagViewModel>()
.ForMember(d => d.Quantity, o => o.MapFrom(s => s.TagPost.Count);
关于asp.net-core - 在 AfterMap 方法 (AutoMapper) 中异步设置 View 模型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46074748/