Reputation: 59
I have a question about making projections with the Entity Framework.
I have three tables: Profile, Biography and BiographyTranslation
I want to do the following projection: (biographies = IQueryable)
return biographies.Select(b => new ProfileBiography
{
Id = b.BiographieID,
OwnerId = b.Profile.ProfileID,
Translations =
b.Translations.Select(t => new DocumentTranslation()
{
DocumentId = b.BiographieID,
FileName = t.BiographyTextFile,
Title = t.Title,
Text = t.Text,
LanguageId = t.LanguageID
})
}
My Problem: The OwnerId is projected correctly, but the number of translations are always 0.
Does projection not work on collection properties?
I also tried biographies.Inlcude("Translations"), but the result was the same.
I created a small Test Project you can find here:
Just 3 tables (create and insert statements included),an EDMX file and a class to load biographies. I still can't get it to work to project a collection navigation property, simple navigation properties work fine. Maybe someone can see from the test project what I'm doing wrong....
I tried a new approach, but still no luck:
using (var context = new DatabaseEntities())
{
return context.BiographySets
.Where(bio => bio.ProfileId == profileId)
.Select(bio => new DocumentModel()
{
Id = bio.Id,
OwnerId = bio.Profile.Id,
Translations = context.BiographyTranslationSets.Where(t => t.BiographyId == bio.Id)
.Select(t => new DocumentTranslation()
{
DocumentId = bio.Id,
LanguageId = t.LanguageId,
Text = t.Text
})
}).ToList();
}
If I use an anonymous type it surprisingly works...
using (var context = new DatabaseEntities())
{
return context.BiographySets
.Where(bio => bio.ProfileId == profileId)
.Select(bio => new
{
Id = bio.Id,
OwnerId = bio.Profile.Id,
Translations = bio.Translations
.Select(t => new
{
DocumentId = bio.Id,
LanguageId = t.LanguageId,
Text = t.Text
})
}).ToList();
}
Upvotes: 4
Views: 4220
Reputation: 59
Ok, I found the problem:
this was my class for the DocumentModel:
public class DocumentModel
{
public DocumentModel()
{
_translations = new List<DocumentTranslation>();
}
public int Id { get; set; }
public int OwnerId { get; set; }
private List<DocumentTranslation> _translations;
public IEnumerable<DocumentTranslation> Translations
{
get { return _translations; }
set { _translations = value.ToList(); }
}
}
And here was the problem:
set { _translations = value.ToList(); }
I can't call ToList() in my Setter because it will break the query.
Upvotes: 1