我有一个表'评论',我想存储日期的评论列表。这些注释可以属于三个不同的类,每个类在db上都有自己的表。 我的第一次尝试是这样做的:
public class Comment
{
public int CommentID { get; set; }
public virtual int OwnerID { get; set; }
public string Description { get; set; }
}
但是我无法弄清楚如何将它与三个不同的类一起使用。
我的下一个选择是:
public class Comment
{
public int CommentID { get; set; }
public virtual IAcceptComment Owner { get; set; }
public string Description { get; set; }
}
我将接口分配给三个类但是我在尝试为其中一个实体配置上下文时遇到错误:(存在显式转换(你是否错过了转换?)
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Event>().HasMany<Comment>(e => e.Comments).WithMany(c => c.Owner);
}
我使用Model First来了解EF如何生成类,这就是它的作用:
public class Comments
{
public int Id { get; set; }
public string Comment { get; set; }
public virtual ICollection<Consultant> Consultant { get; set; }
public virtual ICollection<Event> Event { get; set; }
public virtual ICollection<Company> Company { get; set; }
}
有没有办法避免创建导航属性?你能想到问题的任何其他近似值吗?
感谢。
答案 0 :(得分:0)
我认为您可以在EF中使用继承
这将有助于您避免导航特性
像这样进行查询
'var db = new MySchoolEntities();
foreach (var department in db.Departments)
{
Console.WriteLine();
Console.WriteLine("The {0} department has the following courses:",
department.Name);
Console.WriteLine();
Console.WriteLine(" All courses");
foreach (var course in department.Courses)
{
Console.WriteLine(" The Course Name {0}", course.Title);
}
Console.WriteLine();
if (department.Courses.OfType<OnlineCourse>().Count() > 0)
{
Console.WriteLine(" Online courses are");
foreach (var online in department.Courses.OfType<OnlineCourse>())
{
Console.WriteLine("Online Course is {0} & Link : {1} ", online.Title, online.URL);
}
}
Console.WriteLine();
Console.WriteLine(" Onsite courses are");
foreach (var onsite in department.Courses.OfType<OnsiteCourse>())
{
Console.WriteLine(" Online Course Venue : {0} ", onsite.Location);
}
}
Console.ReadLine();
希望这会让你避免冗长的导航。