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.
There is no real answer to this. I have encountered this more often then not. keeping the order of assignment same as the order of reading help. ie. in Debug time if you see the QueryText and see in what order the columns are read from db. and then keep the assignment same as the order of sql Select Statement in QueryText. Resolves the problem 9 out of 10 times.
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.
来源:https://stackoverflow.com/questions/1734146/subsonic-3-linq-projecting-anonymous-types-but-not-class-types