I am trying to create a list of POCOs from my database. The POCO class has a List<int> property which I want to populate like so:
public List<Pocos.MyTable> GetData()
{
using (EFContext c = new EFContext())
{
var query = from t in c.MyTable
select new Pocos.MyTable()
{
MyId = t.MyId,
MyField = t.MyField,
MyRelationIds = t.MyRelations.Select(mr => mr.MyRelationId).ToList()
};
return query.ToList();
}
}
Unfortunately I am getting the “this method cannot be translated into a store expression” on the ToList()in the query. Can I do this nicely here, or do I have to do lots of subsequent queries to populate the MyRelationIds property?
From your code and description I got, that if try to just use
MyRelations, it is not loaded. And then you try to populetaMyRelationsIdsduring query. There are two ways to solve this. I personally prefer the first one:MyRelationsproperty withpublic virtual List<Relation> MyRelations. Virtual is a convention, after which EF will create a proxy, that will act as a lazy property. I.e. it will be loaded as soon as you touch it.Another way is to use eager loading, with it you don’t have to change the signature.
Just use
Includemethod, to tell EF which props do you want to load eagerly.See that
.Include("MyRelations")it tell, that MyRelations must be loaded during this query. So you can use them later. And if you want to have only ids of relations, then you should first materialize your objects and then do mapping (noteAsEnumerable())