c# - 在 C# 中为 Dapper 创建动态类型

标签 c# dapper

我有一个应用程序,我在其中保存未知的结构化数据。因此,让我们暂时假设数据库中有一个名为 Foo 的表。它看起来像这样:

CREATE TABLE [dbo].[Foo]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [DataId] INT NOT NULL, 
    [Bar] VARCHAR(50) NOT NULL, 
    CONSTRAINT [FK_Foo_Data] FOREIGN KEY ([DataId]) REFERENCES [Data]([Id])
)

Foo与名为 Data 的表相关这将存储记录数据的提供者以及记录数据的日期和时间,假设该表如下所示:

CREATE TABLE [dbo].[Data]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [ProviderId] INT NOT NULL, 
    [RecordDateTime] DATETIME NOT NULL, 
    CONSTRAINT [FK_Data_Provider] FOREIGN KEY ([ProviderId]) REFERENCES [Provider]([Id])
)

好的,现在让我们假设提供者(我不知道它提供的数据)有一个名为 Foo 的类看起来像这样:

[Serializable]
public class Foo : ISerializable
{
    private string bar;

    public string Bar
    {
        get { return bar; }
        set { bar = value; }
    }

    public Foo()
    {
        Bar = "Hello World!";
    }

    public Foo(SerializationInfo info, StreamingContext context)
    {
        this.bar = info.GetString("Bar");
    } 

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Bar", bar);
    }
}

因此,当提供商向我发送 Foo 的实例时我将询问它并确定它应该插入到数据库中的哪个表中,让我们假设代码块如下所示:

this.connection.Open();

try
{
    var parameters = new
        {
            ProviderId = registeredProvidersIdBySession[providerKey.ToString()],
            RecordDateTime = DateTime.Now,
        };

    var id = connection.Query<int>("INSERT INTO Data (ProviderId, RecordDateTime) VALUES (@ProviderId, @RecordDateTime); SELECT CAST(SCOPE_IDENTITY() as INT)", parameters).Single();

    var t = data.GetType();
    var fields = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);

    var tableName = string.Format("[{0}]", t.Name);
    var fieldList = string.Join(", ", fields.Select(p => string.Format("[{0}]", p.Name)).ToArray());

    var valueList = fields.Select(p => string.Format("@{0}", p.Name)).ToList();
    valueList.Insert(0, "@DataId");

    var values = new Dictionary<string, object>();
    values.Add("@DataId", id);
    foreach (var propertyInfo in fields)
    {
        values.Add(string.Format("@{0}", propertyInfo.Name), propertyInfo.GetValue(data, null));
    }

    return connection.Execute(string.Format(
        "INSERT INTO {0} ({1}) VALUES ({2})",
            tableName,
            fieldList,
            string.Join(", ", valueList.ToArray())), values);
}
finally
{
    this.connection.Close();
}

现在如您所见,我得到了 tableName来自 Type传递给我的对象。在我们的例子中是 Foo .此外,我正在收集要通过反射插入的字段列表。然而,相处的障碍是Dapper需要将对象发送给它以获得参数值。现在,如果我不需要提供 DataId我可以传入给我的对象的类型属性,但我需要那个 DataId属性,以便我可以正确关联日志。

我在问什么?

  1. 我必须创建一个动态类型还是可以 Dapper做点别的事来帮忙吗?
  2. 如果我必须创建动态类型,有没有比使用 TypeBuilder 更直接的方法? ?我以前做过,可以再做一次,但伙计,这很痛苦。
  3. 如果我必须使用 TypeBuilder我会对您的示例感兴趣,因为您可能知道比我更有效的方法。因此,如果您有任何想法,请提供示例。

免责声明

在上面的代码示例中,您看到我尝试传入 Dictionary<string, object>而不是Dapper不接受那个。我几乎知道它不会,因为我已经查看了源代码,但我只是希望我错过了一些东西。

谢谢大家!

最佳答案

Dapper 中有一个 BuiltIn 类型来传递参数,其属性仅在运行时已知: 检查类 DynamicParameters。它的用法如下:

var p = new DynamicParameters();
p.Add("@a", 11);
p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output);
p.Add("@c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

然后作为参数对象传递给Execute 方法。它通常与 SP 一起使用(因此您也可以使用它来读取输出值)但没有理由阻止它与常规 SELECT/INSERT/UPDATE 查询一起使用。

关于c# - 在 C# 中为 Dapper 创建动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12515773/

相关文章:

c# - 如何在 .NET Core 中使用 Angular 4 在同一提交中发布表单数据和文件

c# - 我如何重写它以使其更加 LINQy?

transactionscope - 短小精悍和交易范围?

c# - Dapper 性能结果在我的机器上看起来非常相似

c# - Dapper 使用列表插入数据库

c# - 具有始终相等编号的 GUID

c# - 使用 null-coalescing 替代 try catch block

c# - 从 VB 转换为 C#,存储子例程中的值

c# - 计算即将到来的工作日的日期时间

dapper - 如何在 Dapper 中使用 dapper.fluentmap?