Question

I’m trying to develop some basic web app. I will post question with only two entities Article and Image.

One article has many images, and one or more images belong to only one article. Every article implements interface IArticle and abstract class ArticleBase. ArticleBase defines only common properties for each article but child articles can have more properties beside those defined in ArticleBase.

So I have (IArticle, ArticleBase, ArticleComputer, ArticleCar)

public abstract class ArticleBase : Entity, IArticle 
{ 
  ...
  public string Name { get; set; }
  public DateTime Created { get; set; } 
}

public class ArticleComputer : ArticleBase
{
   public virtual IList<Image> Images {get; set;}
   public virtual OSTypeEnum OS {get; set;}
   ...
}

public class ArticleCar : ArticleBase
{
   public IList<Image> Images {get;set;}
   public virtual EngineTypeEnum EngineType {get; set;}
   ...
}

public class Image : Entity<Guid>
{
    public virtual IArticle Article {get; set;}
}

So my question would be: how should I map Image object since I do not want to map every Article which implements IArticle independently?

public class ImageMap : ClassMapping<Image>{
   public ImageMap()  {
     Id(x => x.Id, m => m.Generator(Generators.Identity));
            ManyToOne(x => x.Article, m =>
            {
                m.NotNullable(true);
            });
        }
    }
Was it helpful?

Solution

Why not create an interim abstract class

public abstract class ImageArticle : ArticleBase
{
    public virtual IList<Image> Images { get; protected set; }
}

So ComputerArticle : ImageArticle, etc and Image becomes:

public class Image : Entity<Guid>
{
    public virtual ImageArticle Article { get; set; }
}

And map: (I normally use Fluent NHibernate so apologies if this is the incorrect syntax)

public class ImageArticleMapping : SubclassMapping<ImageArticle>
{
    public ImageArticleMapping()
    {
        this.Bag(x => x.Images)
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top