将一个实体复制到另一个实体以进行缓存

时间:2020-07-12 19:11:40

标签: c# asp.net-core

我正在使用缓存表从api存储项,它是一个大约20个文件的简单表,我正在执行以下操作。

/// <summary>
/// Store the relationship in sql lite database this will be our cache
/// </summary>
/// <param name="realtionship"></param>
public async void RelationShipCache(Vessels ships) {
        // Get an absolute path to the database file
    VesselsCache newCacheObject = new VesselsCache();
    newCacheObject.IMONumber = ships.IMONumber;
    newCacheObject.IMOCompanyNumber = ships.IMOCompanyNumber;
    newCacheObject.GrossTonnage = ships.GrossTonnage;
    this.VesselsCache.Add(newCacheObject);
    await this.SaveChangesAsync();

}

我最好用Automapper https://docs.automapper.org/en/stable/Getting-started.html来做到这一点,如果可以的话,我该怎么做像上面一样简单的事情,或者可以像我一样做。

1 个答案:

答案 0 :(得分:0)

是的,您可以在此处使用自动映射器。首先,您应该确定要使用的源和目标类型。从您的代码中,Vessels是源类型,VesselsCache是目标类型。然后,按照文档进行操作,代码如下所示:

var config = new MapperConfiguration(cfg => cfg.CreateMap<Vessels, VesselsCache>());
var mapper = new Mapper(config);
VesselsCache newCacheObject = mapper.Map<VesselsCache>(ships);

不要忘记从NuGet软件包中安装AutoMapper.Extensions.Microsoft.DependencyInjection