[英]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.