I am using dapper to map SQL result set directly to my C# object, everything works nicely.
I am using statements like this to do the mapping
var result = connection.Query< MyClass >( "sp_select", );
but this statement doesn't seem to enforce exact mapping between the class fields and the columns returned from the database. Meaning, it won't fail when the field on the POCO doesn't exist on the result set.
I do enjoy the fact that the implementation is loose and doesn't enforce any restriction right of the bat, but is there any feature of dapper that would allow me to demand certain fields from the result set before deeming the mapping successful?
You can also try Dapper-Extensions
Here is an example:
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);
}
}
The test will fail due to a missing Address column in the Person table.
You can also ignore columns with Custom Maps:
public class PersonMapper : ClassMapper<Person>
{
public PersonMapper()
{
Map(x => x.Address).Ignore();
AutoMap();
}
}
There is no way for you to enforce this "automagically" with an attribute or a flag. You can follow this open Github issue for more background.
This could be accomplished by you manually by mapping each property yourself in a select clause, although at that point you've lost a lot of the power and ease of use of Dapper.
var result = connection.Query<MyClass>("sp_select")
.Select(x =>
{
// manually map each property and verify
// that the data is returned
});