簡體   English   中英

Dapper - 使用嵌套對象插入

[英]Dapper - Insert using nested object

我有一個帶有嵌套類Bank的類User

class User{
        int Id;
        string username;
        Bank bank;

    }

    Class Bank{
        int id;
        string name;
    }

我需要為User創建一個 Insert 函數。 Dapper有沒有辦法執行查詢並綁定來自嵌套對象的參數?

您可以使用DapperExtensionsDapper編寫自定義映射器:

public sealed class UserMapper : ClassMapper<User>
{
    public UserMapper()
    {
        Map(x => x.bank.id).Column("BankId");
        Map(x => x.bank.name).Column("BankName");

        AutoMap();
    }
}

https://github.com/tmsmith/Dapper-Extensions/wiki/Customized-mapping-for-a-class

確保注冊包含映射器的程序集:

DapperExtensions.SetMappingAssemblies(new[] { typeof(UserMapper).Assembly });

對於不僅User對象而且List<User>可能還需要數據庫插入的這種情況,您可以考慮使用table valued parameters 對於您的問題,它將是:

  • 使用IEnumerable<User>IEnumerable<Bank> ,即使它只是一個對象

  • 使用適當的架構和與存儲過程的IEnumerable collection相同的columns順序制作TVP ,否則會導致錯誤

  • 您可以使用dynamic parameters來綁定參數,其中對於TVPIEnumerable可以使用擴展方法AsTableValuedParameters ,以防您使用anonymous type參數而不是dynamic parameters ,然后使用FastMember中 FastMember 的ObjectReaderIEnuemrable<T>轉換為Datatable ,這對於 TVP 是強制性的。 甚至自定義代碼也可用於IEnuemrable<T>Datatable轉換,以防需要省略幾列,以下是代碼片段:


public static DataTable CreateTable<TDataTable>(this IEnumerable<TDataTable> collection)
{
    // Fetch the type of List contained in the ParamValue
    var tableType = typeof(TDataTable);

    // Create DataTable which will contain data from List<T>
    var dataTable = new DataTable();

    // Fetch the Type fields count
    var columnCount = tableType.GetProperties().Count();

    var columnNameMappingDictionary = new Dictionary<string, string>();

    // Create DataTable Columns using table type field name and their types
    // Traversing through Column Collection
    for (var counter = 0; counter < columnCount; counter++)
    {
        var propertyInfo = tableType.GetProperties()[counter]; 

        var columnName = propertyInfo.Name;

        columnNameMappingDictionary.Add(propertyInfo.Name,
            propertyInfo.Name);

        // Fetch the current type of a property and check whether its nullable type before adding a column
        var currentType = tableType.GetProperties()[counter].PropertyType;

        dataTable.Columns.Add(columnName, Nullable.GetUnderlyingType(currentType) ?? currentType);
    }

    // Return parameter with null value
    if (collection == null)
        return dataTable;

    // Traverse through number of entries / rows in the List
    foreach (var item in collection)
    {
        // Create a new DataRow
        var dataRow = dataTable.NewRow();

        foreach (var columnName in columnNameMappingDictionary.Select(propertyinfo => propertyinfo.Value))
        {
            dataRow[columnName] = item.GetType().GetProperty(columnName).GetValue(item) ?? DBNull.Value;
        }
        // Add Row to Table
        dataTable.Rows.Add(dataRow);
    }

    return (dataTable);
}

暫無
暫無

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

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