簡體   English   中英

您可以使用automapper對所有非映射屬性執行特定操作嗎?

[英]Can you do a specific action with all non mapped properties using automapper?

我正在實現一個導入功能,它將讀取電子表格文件並將所有行保存為DB記錄。 我已經有代碼將電子表格轉換為DataSet

我現在DataRows的問題是我需要將DataRows反序列化的類是這樣的:

public class Product
{
    public string Name { get; set; }

    // More Props

    public IDictionary<string, object> Specifications { get; set; }
}

每個DataRow都將具有所有Product屬性和一些額外的必須添加到Specifications Dictionary

有沒有辦法配置AutoMapper將目標中所有不存在的屬性映射到Specifications Dictionary的新項目?

您無法執行特定操作,但可以創建自定義映射,查找所有未映射的屬性並將其添加到目標字典。

這有點棘手,因為您是從DataRow而不是普通類映射,但它可以完成。 Specifications的解決方法中,您需要遍歷DataTable的列,並檢查是否存在具有該名稱的屬性的映射。 如果沒有將它添加到字典中:

    private static void ConfigureMappings()
    {
        Mapper.CreateMap<DataRow, Product>()
            .ForMember(p => p.Name, mo => mo.MapFrom(row => row["Name"]))
            .ForMember(p => p.ID, mo => mo.MapFrom(row => row["ID"]))
            .ForMember(p => p.Specifications, mo => mo.ResolveUsing(MapSpecifications));
    }

    private static object MapSpecifications(ResolutionResult rr, DataRow row)
    {
        Dictionary<string, object> specs = new Dictionary<string, object>();

        // get all properties mapped in this mapping
        var maps = rr.Context.Parent.TypeMap.GetPropertyMaps();

        // loop all columns in the table
        foreach (DataColumn col in row.Table.Columns)
        {
            // if no property mapping exists, get value and add to dictionary
            if (!maps.Any(map => map.DestinationProperty.Name == col.ColumnName))
            {
                specs.Add(col.ColumnName, row[col.ColumnName]);
            }
        }

        return specs;
    }

示例dotnetFiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM