【发布时间】:2018-08-20 04:02:19
【问题描述】:
我正在尝试解决一个难题,但到目前为止没有运气。
我有一篇文章(或博客文章)和评论实体,它们都有内容。为了支持内容的延迟加载(当我需要显示文章列表或 cmets 时不需要加载内容),我决定将内容移动到单独的表格并组织一对一的映射。这是我的想法的一个例子:
public class Content {
[Key]
public int ID { get; set; }
public string RawContent { get; set; }
// a bunch of scalar properties, like content type and so on
}
public class BlogArticle {
[Key]
public int ID { get; set; }
public int ContentID { get; set; }
[ForeignKey(nameof(ContentID)]
public virtual Content Text { get; set; }
// other properties related to BlogArticle
}
public class Comment {
[Key]
public int ID { get; set; }
public int ContentID { get; set; }
[ForeignKey(nameof(ContentID)]
public virtual Content Text { get; set; }
// other properties related to comment
}
<...>
乍一看似乎没问题:我可以创建博客文章、cmets 和附加内容(起初我插入内容,很明显)。更新也有效。但是,删除不起作用:当我删除博客文章或评论时,内容并没有被删除(但我想在删除博客文章或评论时删除它,而不是相反)。
据我了解,由于关系方向,我最大的问题是:在我的情况下,Content 实体是主体端,BlogArticle 和 Comment 是依赖端。为了解决这个难题,我需要改变主体/依赖关系。同样,据我了解,为了改变关系方向,我需要在Content 实体中有一个外键,并使用流畅的 API 来描述一对一关系中谁是父(主)和谁是子(依赖) .由于许多表(可能还有其他具有 content 属性的实体)都指向Content 表,这似乎并不容易。我的理解正确吗?
我可以想象的一个可能的解决方案是在Content 表中创建多个外键并指向每个相关表:
public class Content {
[Key]
public int ID { get; set; }
public string RawContent { get; set; }
// foreign keys
public int BlogArticleID { get; set; }
public int CommentID { get; set; }
public int WebWidgetID { get; set; }
// other foreign keys if necessary
}
可能,外键必须可以为空(因为一次只能使用一个外键)。然后使用 Entity Framework fluent API 来描述关系方向并组织级联删除。对我来说它看起来很丑,但我没有其他想法。
我的问题:我提出的解决方案是否良好/可靠?还有其他选择吗?
提前致谢!
【问题讨论】:
标签: entity-framework entity-framework-core relationship ef-core-2.0