【发布时间】:2016-07-13 09:33:42
【问题描述】:
我正在尝试在 C# 中创建一个多态关系,类似于 laravel 提供的可以拥有诸如 Uploads 和 它有两个属性叫uploadable_id 和uploadable_type
+----+---------------+-------------------+------------------------------------+
| id | uploadable_id | uploadable_type | file_path |
+----+---------------+-------------------+------------------------------------+
| 1 | 2 | Post | uploads/xyz |
| 2 | 6 | comment | uploads/abc |
+--------------------+-------------------+------------------------------------+
如果我们想在未来添加另一个有很多上传的模型,我们只需要在 uploadable_type 中添加它 无需在上传表中添加更多像 something_id 这样的字段。
我尝试在 C# 中使用抽象类来做类似的事情,如下所示:
public abstract class AttachableEntity
{
public int Id { get; set; }
public ICollection<Upload> Files { get; set; }
}
public class Post : AttachableEntity
{
// other properties
}
public class Comment : AttachableEntity
{
public int PostId { get; set; }
public virtual Post Post { get; set; }
// other properties
}
public class Upload
{
public int Id { get; set; }
public string Filename { get; set; }
public int AttachableEntityId { get; set; }
public AttachableEntity AttachableEntity { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Post> Post { get; set; }
public DbSet<Comment> Comment { get; set; }
public DbSet<Upload> Upload { get; set; }
}
但是当我添加迁移并更新数据库时,它会生成一个名为 AttachableEntity 的表,其中包含来自 所有继承这个抽象类的模型?
如果 AttachableEntity 是抽象的,为什么会生成一个名为 AttachableEntity 的表而没有生成 Post 或 Comment 表?
【问题讨论】:
标签: c# entity-framework oop inheritance polymorphism