如何在样板 AppService 中禁用子实体的变更状态跟踪

How to disable changestate tracking for a sub-entity in boilerplate AppService

我正在将 aspnet core 和 ef core 与样板一起使用,并且想禁用子实体的变更状态跟踪。我如何在 AppService(即 AsyncCrudAppService)中执行此操作。

例如:

实体:

[Table("tblCategory")]
public class Category : FullAuditedEntity<int>, IMustHaveTenant
{
    public const int MaxCodeLength = 128;
    public const int MaxNameLength = 2048;

    public virtual int TenantId { get; set; }

    [Required]
    [StringLength(MaxCodeLength)]
    public virtual string Code { get; set; }

    [Required]
    [StringLength(MaxNameLength)]
    public virtual string Name { get; set; }

    [ForeignKey("GroupId")]
    public virtual Group Group { get; set; }
    [Required]
    public virtual int GroupId { get; set; }
}

Dto:

[AutoMapFrom(typeof(Category))]
public class CategoryDto : FullAuditedEntityDto<int>
{
    [Required]
    [StringLength(Category.MaxCodeLength)]
    public string Code { get; set; }

    [Required]
    [StringLength(Category.MaxNameLength)]
    public  string Name { get; set; }

    [Required]
    public  int GroupId { get;  set; }

    [DisableValidation]
    public GroupDto Group{ get;  set; }

}

应用服务更新方法:

public override async Task<CategoryDto> Update(CategoryDto input)
{
    var cat = await _categoryManager.GetA(input.Id);

    MapToEntity(input, cat);

    //I'd like to disable the tracking of cat.Group here ?

    await _categoryManager.UpdateA(cat);

    return await Get(input);
}

我想禁用 cat.Group 的变化检测,我该怎么做?

提前致谢。

加载时使用 AsNoTracking 解决了问题

可以通过在调用中添加 .AsNoTracking() 来跳过跟踪。

例如:

var cat = await _yourDbContext.AsNoTracking().FirstAsync(m => m.Id == input.Id);

这适用于在其生命周期内不会被编辑的结果。