使用Automapper隐藏数据库主键/ID(使用ValueConverter转换成员)



我试图使用Automapper的值转换器隐藏数据库中对象的真实id,但是它们在投影到另一个时不被调用。

没什么特别的,我想使用Hashids将int ID转换为随机字符串ID (DB->DTO),反之亦然。我想对每个对象和ID都这样做,但不是我的转换器被调用而是数据库中的ID被转换成字符串(1变成"1")而不是例如"sd2+a!F")。

我的类:

public class Category
{
public Category(string name)
{
Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
public int? ParentCategoryId { get; set; }
public Category? ParentCategory { get; set; }
public ICollection<Foodstuff> Foodstuffs { get; } = new List<Foodstuff>();
public ICollection<int> FoodstuffIds { get; } = new List<int>();
public byte[] RowVersion { get; set; }
}

我的DTO。

public record class Category : IGenerateETag
{
public Category(string name)
{
Name = name;
}
public string Id { get; init; }
[Required(ErrorMessage = "Category name is required.", AllowEmptyStrings = false)]
public string Name { get; init; }
public string? ParentCategoryId { get; init; }
public byte[] RowVersion { get; set; }
}

我的转换器:

public class HideIdConverter : IValueConverter<int, string>
{
public string Convert(int sourceMember, ResolutionContext context)
{
var hashids = new Hashids();
var shadow = hashids.Encode(sourceMember);
return shadow;
}
}

public class UnhideIdConverter : IValueConverter<string, int>
{
public int Convert(string sourceMember, ResolutionContext context)
{
var hashids = new Hashids();
var plain = hashids.Decode(sourceMember);
return plain[0]; // TODO check this;
}
}

a和我的Automapper配置:

CreateMap<Dal.Entities.Category, Category>()
.ForMember(dest => dest.Id, opt => opt.ConvertUsing(new HideIdConverter(), src => src.Id))
.ReverseMap()
.ForMember(dest => dest.Id, opt => opt.ConvertUsing(new UnhideIdConverter(), src => src.Id));

事实证明,这是不可能的,因为我使用LINQ表达式,特别是ProjectTo()。如:

值转换器仅用于在内存中执行映射。他们不会为ProjectTo工作。

来源。我想我必须在之后映射对象我从数据库中查询了它们。

最新更新