2016-08-17 35 views
1

我正在使用dapper將SQL結果集直接映射到我的C#對象,一切正常。如何在Dapper上執行嚴格映射

我使用這樣的語句進行映射

變種結果= connection.Query < MyClass的>( 「sp_select」,);

但是這個語句似乎沒有強制實現類字段和從數據庫返回的列之間的精確映射。意思是,當POCO上的字段不存在於結果集上時,它不會失敗。

我確實喜歡這樣一個事實,即實現是鬆散的,並且不會強制執行任何蝙蝠限制權限,但是有什麼功能可以讓我在認爲映射成功之前請求結果集中的某些字段?

回答

1

您也可以嘗試Dapper-Extensions

下面是一個例子:

public class Person 
{ 
    public int Id { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string Address { get; set; } 
} 

[TestFixture] 
public class DapperExtensions 
{ 
    private SqlConnection _connection; 

    [SetUp] 
    public void Init() 
    { 
     _connection = new SqlConnection(@"Data Source=.\sqlexpress;Integrated Security=true; Initial Catalog=mydb"); 
     _connection.Open(); 

     _connection.Execute("create table Person(Id int not null, FirstName varchar(100) not null, LastName varchar(100) not null)"); 
     _connection.Execute("insert into Person(Id, FirstName, LastName) values (1, 'Bill', 'Gates')"); 
    } 

    [TearDown] 
    public void Teardown() 
    { 
     _connection.Execute("drop table Person"); 
     _connection.Close(); 
    } 

    [Test] 
    public void Test() 
    { 
     var result = _connection.Get<Person>(1); 
    } 
} 

,測試將失敗歸因於Person表缺少地址欄。

您也可以忽略列與Custom Maps

public class PersonMapper : ClassMapper<Person> 
{ 
    public PersonMapper() 
    { 
     Map(x => x.Address).Ignore(); 
     AutoMap(); 
    } 
} 
1

您無法通過屬性或標誌「自動」執行此操作。您可以按照此open Github issue瞭解更多背景。

這可以通過以下方式實現你的,你自己映射每個屬性的選擇條款,雖然在這一點上,你已經失去了很多的力量和易用性小巧玲瓏的手動

var result = connection.Query<MyClass>("sp_select") 
         .Select(x => 
         { 
          // manually map each property and verify 
          // that the data is returned 
         }); 
+0

感謝您指出在GitHub上懸而未決的問題,我肯定有人已經要求在某些時候這個功能...我只是沒有得到在我的搜索中正確的措辭。它有道理,他們爲什麼抵制迅速添加功能。 –