Dapper .Net:表列和模型属性类型不匹配

时间:2013-07-10 04:18:35

标签: dapper

实际上我有一个查询返回包含varchar类型的列(对于ex.Address)的结果,但是该表的域模型包含object类型的属性(例如地址)。因为它拖拽错误无法将字符串强制转换为Comment.I无法弄清楚如何使用dapper .net。

解决此问题

代码段:

IEnumerable<Account> resultList = conn.Query<Account>(@"
                    SELECT * 
                    FROM Account
                    WHERE shopId = @ShopId", 
new {  ShopId = shopId });

例如,Account对象。

public class Account {
  public int? Id {get;set;}
  public string Name {get;set;}
  public Address Address {get;set;}
  public string Country {get;set;}
  public int ShopId {get; set;}
}

由于数据库表列(地址)和域模型属性(地址)之间存在类型不匹配,所以dapper会抛出异常。所以有任何方法可以通过精简程序映射该属性..

2 个答案:

答案 0 :(得分:4)

另一种选择是使用Dapper的Multi-Mapping功能。

public class TheAccount
{
    public int? Id { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
    public string Country { get; set; }
    public int ShopId { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
}

public class Class1
{
    [Test]
    public void MultiMappingTest()
    {
        var conn =
            new SqlConnection(
                @"Data Source=.\SQLEXPRESS; Integrated Security=true; Initial Catalog=MyDb");
        conn.Open();

        const string sql = "select Id = 1, Name = 'John Doe', Country = 'USA', ShopId = 99, " +
                           " Street = '123 Elm Street', City = 'Gotham'";

        var result = conn.Query<TheAccount, Address, TheAccount>(sql, 
            (account, address) =>
                {
                    account.Address = address;
                    return account;
                }, splitOn: "Street").First();

        Assert.That(result.Address.Street, Is.Not.Null);
        Assert.That(result.Country, Is.Not.Null);
        Assert.That(result.Name, Is.Not.Null);
    }
}

我看到的唯一问题是,您必须列出所有帐户字段,然后列出select语句中的地址字段,以允许splitOn工作。

答案 1 :(得分:1)

由于您的POCO与数据库之间存在类型不匹配,因此您需要在两者之间提供映射。

public class Account {
  public int? Id {get;set;}
  public string Name {get;set;}
  public string DBAddress {get;set;}
  public Address Address 
  {
   // Propbably optimize here to only create it once.
   get { return new Address(this.DBAddress); } 
  }

  public string Country {get;set;}
  public int ShopId {get; set;}
}

类似的东西 - 您将db列与属性DBAddress匹配(您需要提供SELECT Address as DBAddress而不是*的别名)并在Address对象上提供get方法使用db值的内容创建/重用Address类型。