asp.net-core - 在 AfterMap 方法 (AutoMapper) 中异步设置 View 模型的属性

标签 asp.net-core async-await many-to-many automapper

在我的数据库中,我有标签和帖子表。它们之间是多对多的关系。在标签实体中,我不存储标签使用次数。此属性(Quantity)位于标记 View 模型内。

通过使用AutoMapper,我在TagTagViewModel 之间创建了一个映射。在 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/

相关文章:

asynchronous - Flutter : Failed assertion: line 146: '<optimized out>' : is not true 中的 Dart future 问题

mysql - 高效插入/更新mysql m :n relations

c# - 未设置 ASP.NET Core 2.0 身份验证 Cookie

在azure应用程序服务上运行的Angular应用程序未收到由azure上的.net core Web api应用程序发送的.AspNetCore.Antiforgery cookie

c# - 在面向 .NET Core 的类库包中使用 JsonConvert.DeserializeObject

javascript - Koa中,中间件中的await next()、return await next()、return next()、next()有什么区别?

c# - ASP .Net Core 身份角色声明未添加到用户

c# - 使用 async/await 时防止 winforms UI 阻塞

c# - 使用 TPT 方法的多对多 Entity Framework

php - 从 Laravel 中的 Mysql 数据透视表获取列并返回一个 JSON 对象