2

実際には、varchar 型の列 (例: Address) を含む結果を返すクエリがありますが、オブジェクト型 (例: Address Address) のプロパティを含むテーブルのドメイン モデルです。そのため、キャストできませんでしたというエラーが発生します。この問題を 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;}
}

データベーステーブルの列(アドレス)とドメインモデルのプロパティ(アドレス)の間に型の不一致があるため、ダッパーは例外をスローします。そのプロパティをダッパーでマップする方法はありますか..

4

2 に答える 2

4

もう 1 つのオプションは、Dapper のマルチマッピング機能を使用することです。

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 ステートメントですべての Account フィールドをリストし、続いて Address フィールドをリストして、splitOn が機能するようにする必要があることです。

于 2013-07-10T15:56:54.547 に答える
1

POCO とデータベースの間に型の不一致があるため、2 つの間のマッピングを提供する必要があります。

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(*の代わりにエイリアスを提供する必要があります) 、db値の内容でタイプを作成/再利用するオブジェクトにSELECT Address as DBAddressgetメソッドを提供します。AddressAddress

于 2013-07-10T10:37:11.343 に答える