多态模型的概念。例如,我们有这个表评论:
+----+---------------+-------------------+------------------------------------+
| id | commentable_id| commentable_type | comments_text |
+----+---------------+-------------------+------------------------------------+
| 1 | 2 | youtube | youtube rocks, buddy! |
| 2 | 6 | vimeo | hey, vimeo is better! |
+--------------------+-------------------+------------------------------------+
class Youtube(){…}
和class Vimeo(){…}
youtube可以有很多评论,vimeo可以有很多评论,评论属于youtube和vimeo。 commentable_type
中添加该模型,而无需在评论表中添加更多字段something_id
。 commentable_type
中添加dailymotion,而无需在评论表中添加字段dailymotion_id
commentable_id = 2
在youtube表中引用youtube_id = 2
,commentable_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操作?
答案 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; }
}
查询时会创建以下结构:
要访问它,您必须执行以下操作:
var context = new VideoContext();
var vimeos = context.Vimeos.Include(x => x.Comments).ToList();
var youtubes = context.Youtubes.Include(x => x.Comments).ToList();
答案 1 :(得分:0)
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;}
}