// From my form
BindingSource bs = new BindingSource();
private void fillStudentGrid()
{
     bs.DataSource = Admin.GetStudents();
     dgViewStudents.DataSource = bs;
}
// From the Admin class
public static List<Student> GetStudents()
{
    DojoDBDataContext conn = new DojoDBDataContext();
    var query =
        (from s in conn.Students
         select new Student
         {
             ID = s.ID,
             FirstName = s.FirstName,
             LastName = s.LastName,
             Belt = s.Belt
         }).ToList();
    return query;
}
I'm trying to fill a datagridview control in Winforms, and I only want a few of the values. The code compiles, but throws a runtime error:
Explicit construction of entity type 'DojoManagement.Student' in query is not allowed.
Is there a way to get it working in this manner?
You already have an IEnumerable<Student> instance and you cannot project entities from a query for the reasons described here)
You also don't need to create a list to bind to this data source - you can greatly simplify your method by changing it to this:
public static IEnumerable<Student> GetStudents()
{
    return new DojoDBDataContext().Students;
}
There is no reason to project a new instance to only map a few of the properties, by executing the query you are returning all the values anyhow and your projection doesn't save you anything. If you really want to only return a few values from this query for the purposes of information hiding you could do this:
public static IEnumerable<Object> GetStudents()
{
    DojoDBDataContext conn = new DojoDBDataContext();
    return conn.Students
               .Select(s => new {
                   ID = s.ID,
                   FirstName = s.FirstName,
                   LastName = s.LastName,
                   Belt = s.Belt 
               });
}
Edit: If you aren't using C# 4 you will have to cast the contents of the IEnumerable<T> to Object explicitly.  Only C# 4 supports covariance for IEnumerable<T>.  So if you are using C# 3 you will have to do this:
public static IEnumerable<Object> GetStudents()
{
    DojoDBDataContext conn = new DojoDBDataContext();
    return conn.Students
               .Select(s => new {
                   ID = s.ID,
                   FirstName = s.FirstName,
                   LastName = s.LastName,
                   Belt = s.Belt 
               }).Cast<Object>();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With