[英]One to many relationship with junction table using Entity Framework code first
[英]One table to many with Entity Framework Code First
我有一个表“ Comments”,我想存储带有日期的注释列表。 这些注释可以属于三个不同的类,每个类在数据库上都有自己的表。 我的第一次尝试是这样做的:
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; }
}
有没有什么方法可以避免创建导航属性? 您能想到这个问题的其他近似方法吗?
谢谢。
我认为您可以在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();
希望这可以避免冗长的导航。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.