Alphapico
Alphapico

Reputation: 3043

Polymorphic model in ASP MVC?

Concept of polymorphic model. For example we have this table comment:

+----+---------------+-------------------+------------------------------------+
| id | commentable_id| commentable_type  |            comments_text           |
+----+---------------+-------------------+------------------------------------+
|  1 |    2          |      youtube      |        youtube rocks, buddy!       |
|  2 |    6          |       vimeo       |        hey, vimeo is better!       |
+--------------------+-------------------+------------------------------------+

In Laravel (PHP) we can simply do like this:

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

and we can simply access them like this:

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

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

My Questions are, how to derive the relationship of this ORM in ASP MVC? And how we can easily access them to do CRUD operation?

Upvotes: 1

Views: 983

Answers (2)

CallumVass
CallumVass

Reputation: 11448

I'm not sure if this is entirely what you're looking for, but something like this should suffice:

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

This creates the following structure when querying:

enter image description here

To access it you would have to do something like this:

var context = new VideoContext();

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

Upvotes: 1

Krahu
Krahu

Reputation: 183

You can use Inheritance 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;}
}

Upvotes: 0

Related Questions