I’m working on an EntityFramework application and I have run across a problem when using a struct instead of a class with Database.SqlQuery.
The struct looks like this:
internal struct Column
{
public int object_id { get; set; }
public string name { get; set; }
}
and the call to SqlQuery looks like this:
using (var db = new DbContext("ConnectionString"))
{
var columns = db.Database.SqlQuery<Column>(query);
DoSomething(columns.ToList()); // Exception thrown here
}
I get an ArgumentException with the message “Expression of type ‘MyService.Column’ cannot be used for return type ‘System.Object'” when Column is a struct. I changed it to a class and it works fine.
I’m happy enough to use a class here, but I’m wondering why a struct would fail when used in this way.
EntityFramework provides an object oriented representation of your data. Because of that, the result needs to be an object, as it has to maintain state. If you use a struct, the data will be copied every time you pass the column between methods and that makes no sense, as it represent the same value from the database.