Why won't my columns with Data Annotations map when using Entity Framework

梦想与她 提交于 2019-12-14 03:43:55

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/10756722/why-wont-my-columns-with-data-annotations-map-when-using-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!