实体框架代码优先的一个表到多个表

时间:2014-01-25 06:19:31

标签: entity-framework code-first

我有一个表'评论',我想存储日期的评论列表。这些注释可以属于三个不同的类,每个类在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; }

}

有没有办法避免创建导航属性?你能想到问题的任何其他近似值吗?

感谢。

1 个答案:

答案 0 :(得分:0)

我认为您可以在EF中使用继承

Inheritance Refernece

TPT Inheritance Usage msdn

TpT Usages

这将有助于您避免导航特性

像这样进行查询

     '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();

希望这会让你避免冗长的导航。