Reputation: 3043
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! |
+--------------------+-------------------+------------------------------------+
class Youtube(){…}
and class Vimeo(){…}
youtube can has many comments, and vimeo can has many comments, and comment belong to youtube and vimeo. commentable_type
without adding more field like something_id
into comment table. commentable_type
without adding field dailymotion_id
into comment tablecommentable_id = 2
refer to youtube_id = 2
in youtube table, and commentable_id
= 6 refer to vimeo_id
= 6 in vimeo table.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
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:
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
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