views:

167

answers:

2

I am fairly new to SubSonic 3/Linq, and don't know if I'm missing something obvious, but I think I ran into a projection issue. I am trying to perform the most basic query, and getting back proper results only when I use anonymous types. The moment I swap the anonymous types with regular class types, I get all properties set to null/zero. I am crafting a DAL class library, so unfortunately anonymous types are not an option.

Snippet

using System;
using System.Linq;
using Fruits.Data;

namespace FruitTest {

    class Program {
        static void Main(string[] args) {

            var db = new FruitsDB();

            var fruits = from f in db.Fruits
                         select new FruitView {
                             MyFruitID = f.FruitID,
                             MyFruitName = f.FruitName,
                         };

            foreach (var f in fruits) {
                Console.WriteLine(f.MyFruitID + "\t" + f.MyFruitName);
            }

        }
    }

    public class FruitView {
        public int MyFruitID { get; set; }
        public string MyFruitName { get; set; }
    }

}

So this doesn't work (returns all nulls/zeros)

var fruits = from f in db.Fruits
             select new FruitView {
                 MyFruitID = f.FruitID,
                 MyFruitName = f.FruitName,
             };

This works as expected

var fruits = from f in db.Fruits
             select new {
                 MyFruitID = f.FruitID,
                 MyFruitName = f.FruitName,
             };

My problem is somewhat similar to this and this, only I am not even doing joins; just simple selects.

Any clues will be much appreciated.

A: 

Try this instead:

IList<FruitView> fruits = (
         from f in db.Fruits
             select new FruitView {
                 MyFruitID = f.FruitID,
                 MyFruitName = f.FruitName
             }).ToList();

or

IQueryable<FruitView> fruits = 
         from f in db.Fruits
             select new FruitView {
                 MyFruitID = f.FruitID,
                 MyFruitName = f.FruitName
             };

..and foreach as before.

cottsak
Thanks cottsak. I just tried your suggestions but unfortunately I still get nulls with both.
Daniel Liuzzi
A: 

I'm having the same issue. Does anyone have any suggestions on how to deal with this?

Tim Marman