我有多个模型(任务/服务器/等),所有这些模型都需要支持评论。我想要一个所有这些模型都可以参考的集中评论表(尽管我对其他设计持开放态度)。
评论表将包含以下字段:
CommentID
RefTable
RefId
Text
我可以在任务类(例如)中使用以下代码来引用任务的注释。
IEnumerable<Comment> comments = Comment.Find(this.GetType().Name, this.TaskID)
但是,我更愿意创建从任务到注释的 HasMany 映射,以便我可以使用以下代码。
this.Comments
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.ModelConfiguration;
namespace Models.Mapping
{
public class TaskMap : EntityTypeConfiguration<Task>
{
public TaskManagerItemMap()
{
// Primary Key
this.HasKey(t => t.TaskID);
...
this.Property(t => t.TaskID).HasColumnName("TaskID")
...
this.ToTable("Task");
}
}
}
using System;
using System.Collections.Generic;
namespace Models
{
public partial class Task
{
public int TaskID { get; set; }
....
public virtual IEnumerable<Comment> Comments { get; set; }
...
}
}
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.ModelConfiguration;
namespace Models.Mapping
{
public class CommentMap : EntityTypeConfiguration<Comment>
{
public CommentMap()
{
this.HasKey(t => new { t.RefID, t.RefTable });
this.ToTable("Comment");
this.Property(t => t.CommentID).HasColumnName("CommentID")
.IsRequired();
this.Property(t => t.RefID).HasColumnName("RefID")
.IsRequired();
this.Property(t => t.RefTable).HasColumnName("RefTable")
.IsRequired();
this.Property(t => t.Text).HasColumnName("Text")
.IsRequired();
}
}
}
using System;
using System.Collections.Generic;
namespace Models
{
public partial class Comment
{
public int CommentID { get; set; }
public int RefID { get; set; }
public string RefTable { get; set; }
public string Text { get; set; }
}
}
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Globalization;
using Vocus50.SiteManager.SiteManager2014.Models.Mapping;
namespace Models
{
public partial class DataContext : DbContext
{
static DataContext()
{
Database.SetInitializer<DataContext>(null);
}
public DataContext()
: base("Name=DataContext")
{
}
public DbSet<Task> Task{ get; set; }
public DbSet<Comment> Comment { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new TaskMap());
modelBuilder.Configurations.Add(new CommentMap());
}
}
}