Dapper won't read object properties unless explicitly listed as anonymous type

c# dapper

Question

Dapper Query isn't populating parameters from typed objects' properties for some reason.

The following code throws an exception saying I must declare @Username, even though credentials contains property credentials.Username:

const string qryCheckCredentials = "SELECT 1 AS Authenticated FROM dbo.KIUser WHERE Username=@Username AND Password=@PasswordMD5";
if (!sqlConn.Query<Boolean>(qryCheckCredentials, param: credentials).FirstOrDefault<Boolean>())
    throw new UnauthorizedAccessException..

But if I list out the credential properties explicitly into an anonymous object it works fine:

const string qryCheckCredentials = "SELECT 1 AS Authenticated FROM dbo.KIUser WHERE Username=@Username AND Password=@PasswordMD5";
if (!sqlConn.Query<Boolean>(qryCheckCredentials, param: new { Username = credentials.Username, PasswordMD5 = credentials.PasswordMD5 } ).FirstOrDefault<Boolean>())
    throw new UnauthorizedAccessException..

Any ideas why? I'm getting this issue all over my code and can't see a pattern or figure out what I'm missing.

The Credentials type:

[DataContract]
public class Credentials
{
    [DataMember]
    public string Username;
    [DataMember]
    public string PasswordMD5;
}

Happens with many types, and listing through them explicitly fixes the issue.

(The DataContract / DataMember attribute decorations are because the object is part of a WDSL interface - probably irrelevant but left here in case they're relevant for some reason beyond my knowledge.)

Accepted Answer

My best guess is that Dapper only looks at properties, not fields. Try changing your class to the following and see if it works.

[DataContract]
public class Credentials
{
    [DataMember]
    public string Username {get; set;}
    [DataMember]
    public string PasswordMD5 {get; set;}
}

It's generally considered better practice to use public properties anyway.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why