Reputation: 73
I have a class that looks like this:
public class Analyst
{
[Column("Internal_ID")]
public int ID { get; set; } // if this is named like the column, it works
[Column("DisplayName")]
public string Name { get; set; }
}
This object is being filled like so (this next part is in a class which inherits from DbContext):
public List<T> ExecProc<T>(string proc, Dictionary<string, object> params)
{
var parms = new List<SqlParameter>();
var sql = new StringBuilder();
sql.Append(sproc.StoredProcedure);
sql.Append(" "); // a space, that's all it is
foreach (var key in sproc.Parameters.Keys)
{
sql.Append(string.Format("{0},", key));
parms.Add(new SqlParameter(key, sproc.Parameters[key]));
}
if (sql[sql.Length - 1] == ',') // removing the trailing ,
{
sql.Remove(sql.Length - 1, 1);
}
return Database.SqlQuery<T>(sql.ToString(), parms.ToArray()).ToList();
}
The returned List contains the correct amount of rows (or objects in this case), but none of the properties are populated with values. If the proc returns 200 rows, then I get 200 objects in the List, but none of them have any values populated.
I have verified that there is no mismatch between the field names and the values in the [Column("name")] attribute. If i change the property names to match the field names in the result set, then it works fine, but I cannot seem to get it to work if I try mapping them using the Data Annotations. Can anyone please point out what I'm missing here? I'm certain that it's something simple.
Using: Visual Studio 2010 Ultimate SP1, .Net 4 SP1, EF 4.2.0 (I encountered the same problem with EF 4.3). This is all done using code only, no mapping files are used for this.
Upvotes: 3
Views: 3886
Reputation: 39501
As it seems, this is documented behavior. Database.SqlQuery Method has no direct connection to DbContext model configuration.
Creates a raw SQL query that will return elements of the given generic type. The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type.
So, when using this method, you should construct your sql so that result set column names match property names of type used.
Upvotes: 10