ASP MVC中的多态模型?

时间:2014-03-20 09:34:49

标签: c# asp.net sql asp.net-mvc polymorphism

多态模型的概念。例如,我们有这个表评论:

+----+---------------+-------------------+------------------------------------+
| id | commentable_id| commentable_type  |            comments_text           |
+----+---------------+-------------------+------------------------------------+
|  1 |    2          |      youtube      |        youtube rocks, buddy!       |
|  2 |    6          |       vimeo       |        hey, vimeo is better!       |
+--------------------+-------------------+------------------------------------+
  • youtube和vimeo在哪里引用模型class Youtube(){…}class Vimeo(){…} youtube可以有很多评论,vimeo可以有很多评论,评论属于youtube和vimeo。
  • 如果我们希望在将来添加另一个包含许多评论的模型,我们只需在commentable_type中添加该模型,而无需在评论表中添加更多字段something_id
  • 如果我们想添加dailymotion,我们只需在commentable_type中添加dailymotion,而无需在评论表中添加字段dailymotion_id
  • commentable_id = 2在youtube表中引用youtube_id = 2commentable_id = 6在vimeo表中引用vimeo_id = 6。

在Laravel(PHP)中,我们可以这样做:

class Youtube extends Eloquent{

    public function comments()
    {
        return $this->morphMany('Comment', 'commentable');
    }
}

class Vimeo extends Eloquent{

    public function comments()
    {
        return $this->morphMany('Comment', 'commentable');
    }
}

class Comment extends Eloquent{

    public function commentable()
    {
        return $this->morphTo();
    }
}

我们可以像这样访问它们:

$youtube = Youtube::find(1);
$youtube->comments;

$vimeo = Vimeo::find(1);
$vimo->comments;

我的问题是,如何在ASP MVC中推导出这个ORM的关系?我们如何轻松访问它们来进行CRUD操作?

2 个答案:

答案 0 :(得分:1)

我不确定这是否完全是你想要的,但这样的事情就足够了:

public abstract class Video
{
    public int Id { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

public class Youtube : Video
{
    /* Other properties */
}

public class Vimeo : Video
{
    /* Other properties */
}

public class Comment
{
    public int Id { get; set; }
    public string CommentText { get; set; }

    public int VideoId { get; set; }

    public virtual Video Video { get; set; }
}

public class VideoContext : DbContext
{
    public DbSet<Youtube> Youtubes { get; set; }
    public DbSet<Vimeo> Vimeos { get; set; }
    public DbSet<Comment> Comments { get; set; }
}

查询时会创建以下结构:

enter image description here

要访问它,您必须执行以下操作:

var context = new VideoContext();

var vimeos = context.Vimeos.Include(x => x.Comments).ToList();
var youtubes = context.Youtubes.Include(x => x.Comments).ToList();

答案 1 :(得分:0)

您可以使用继承http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application

public class Video {
// Id etc.
public virtual IList<Comment> Comments {get; set;}
}

public class Youtube : Video{
// Id etc.
}

public class Vimeo : Video{
// Id etc.
}

public class Comment {
// comment props
 public virtual IList<Video> Videos {get; set;}
}