entity -> interface relationship, how to map

十年热恋 提交于 2019-12-23 17:23:28

问题


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);
            });
        }
    }

回答1:


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)
    }
}


来源:https://stackoverflow.com/questions/23308220/entity-interface-relationship-how-to-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!