Linq to Entities and POCO foreign key relations mapping (1 to 0..1) problem
- by brainnovative
For my ASP.NET MVC 2 application I use Entity Framework 1.0 as my data access layer (repository). But I decided I want to return POCO. For the first time I have encountered a problem when I wanted to get a list of Brands with their optional logos. Here's what I did:
public IQueryable<Model.Products.Brand> GetAll()
{
IQueryable<Model.Products.Brand> brands = from b in EntitiesCtx.Brands.Include("Logo")
select new Model.Products.Brand()
{
BrandId = b.BrandId,
Name = b.Name,
Description = b.Description,
IsActive = b.IsActive,
Logo = /*b.Logo != null ? */new Model.Cms.Image()
{
ImageId = b.Logo.ImageId,
Alt = b.Logo.Alt,
Url = b.Logo.Url
}/* : null*/
};
return brands;
}
You can see in the comments what I would like to achieve. It worked fine whenever a Brand had a Logo otherwise it through an exception that you can assign null to the non-nullable type int (for Id). My workaround was to use nullable in the POCO class but that's not natural - then I have to check not only if Logo is null in my Service layer or Controllers and Views but mostly for Logo.ImageId.HasValue. It's not justified to have a non null Logo property if the id is null.
Can anyone think of a better solution?