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?
I have another workaround for this. Since in some cases the Image (the class for Logo property) can’t be
nulland in some it can I decided to add some inheritance to my model of the Image. Here’s what I’ve done:Then my repository returns a nullable Id only for the objects that have 0..1 relation with Image – like Brand. But a Product which has a required DefaultImage property will use Image without nullable Id which is corresponding to the database and business logic design.
The
GetAllmethod in the repository now looks like this (thanks @omoto for the tip):For products instead of
new Model.Cms.OptionalImage()I will usenew Model.Cms.Image()and since the value ofImageIddatabase filed in that case can’t be null it will work fine and everything will be natural in the controllers and views.I think this kind of workaround suits my needs very well. Still if anyone has a better solution feel free to reply.