我有 3 个实体,我正在尝试在它们之间创建映射。
[Table("ContentItem")]
public class ContentItem
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public virtual Page Page { get; set; }
[Column("PageID")]
public int PageID { get; set; }
public virtual ContentType ContentType { get; set; }
[Column("ContentTypeID")]
public int ContentTypeID { get; set; }
public int ItemID { get; set; }
}
[Table("ContentType")]
public class ContentType
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string Name { get; set; }
[ForeignKey("ID")]
public virtual HTMLContent HtmlContent { get; set; }
}
[Table("HTMLContent")]
public class HTMLContent
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("ID")]
public int ID { get; set; }
public string Content { get; set; }
public int SortOrder { get; set; }
[Column("PageID")]
public int PageID { get; set; }
[Column("ContentTypeID")]
public int ContentTypeID { get; set; }
public virtual ContentType ContentType { get; set; }
}
我目前使用 Fluent API 映射了 ContentType 和 HTMLContent 之间的关系,如下所示:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// http://weblogs.asp.net/shijuvarghese/archive/2011/10/06/removing-edmmetadata-table-in-ef-code-first.aspx
// We don't need the EdmMetadata table in the DB
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Entity<ContentType>().HasRequired(b => b.HtmlContent);
}
现在使用 Linq 访问 HTMLContent,如下所示:
var contentItems = cmsUnitOfWork.ContentItems.Find().Where(x => x.PageID == 1).ToList();
我可以在我的视图中访问 HTMLContent:
@model IEnumerable<H2O.Domain.CMS.Models.ContentItem>
@foreach(var x in Model)
{
<div id="ContentItem@(x.ID)">
<strong>@x.ContentType.HtmlContent.Content
</div>
}
但是,它只给了我数据库中的第一个 HTMLContent 行。我希望它返回 ID 对应于 ContentItem 实体中的 ItemID 成员的 HTMLContent。由于 ItemID 可能来自 HTMLContent 以外的其他 ID,因此我无法映射直接外键。我怎样才能用实体做到这一点?