本文介绍了实体->接口关系,如何映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发一些基本的网络应用程序.我将发布只有两个实体文章和图片的问题.

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

一篇文章有​​很多图片,一张或多张图片只属于一篇文章.每篇文章都实现了接口 IArticle 和抽象类 ArticleBase.ArticleBase 只为每篇文章定义通用属性,但子文章除了在 ArticleBase 中定义的属性之外,还可以具有更多属性.

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.

所以我有 (IArticle, ArticleBase, ArticleComputer, ArticleCar)

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

所以我的问题是:我应该如何映射 Image 对象,因为我不想映射每个独立实现 IArticle 的文章?

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

推荐答案

为什么不创建一个临时抽象类

Why not create an interim abstract class

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

所以 ComputerArticle : ImageArticle 等和 Image 变成:

So ComputerArticle : ImageArticle, etc and Image becomes:

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

和映射:(我通常使用 Fluent NHibernate,如果语法不正确,请见谅)

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

这篇关于实体-&gt;接口关系,如何映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 01:28