[英]Entity Framework 6 take records that don't exist in table
在MVC動作中
Site site = siteRepository.UserSites(userId).Where(x => x.Order == siteOrder).Last();
在SiteRepository中
public IEnumerable<Site> UserSites(string userId)
{
return context.Sites.Include("Pages").Where(x => x.UserId == userId);
}
和其他存儲庫
public IEnumerable<Row> Items
{
get
{
return context.Rows;
}
}
public IEnumerable<Page> Items
{
get
{
return context.Pages;
}
}
public IEnumerable<AbstractBuildBlock> Items
{
get
{
return context.BuildBlocks;
}
}
我不知道為什么,但是在調試器中,我看到對UserSites的請求(第一個存儲庫代碼段)之后,在Site.Rows中還有一個記錄,這是第一個記錄,它是由Row構造函數創建的,我還沒有任何想法為什么會發生。
這兩個對象具有不同的類型,第一個(我不了解)的類型是Domain.Entities.Row
,第二個System.Data.Entity.DynamicProxies.Row_**********
(*-一些數字)
我再重復一遍。 在我的Rows表中只有一個記錄,但是在Site.Pages [someIndex]中。向數據庫請求后的行有兩個對象,第一個在表中不存在,它是由Row構造函數創建的。 為什么會發生?
網站分類代碼
public class Site
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required(ErrorMessage ="Please, enter the site local name")]
[Display(Name ="Local name")]
public string LocalName { get; set; }
[Required(ErrorMessage = "Please, enter the site public name")]
[Display(Name ="Public name")]
public string PublicName { get; set; }
[Display(Name ="Menu variant")]
public string MenuVariant { get; set; }
[Display(Name = "Color theme")]
public string ColorTheme { get; set; }
public string IconUrl { get; set; }
public string UserId { get; set; }
public int Order { get; set; }
public int NextPageOrder { get; set; }
public virtual List<TopMenuItem> TopMenuItems { get; set; }
public virtual List<LeftMenuItem> LeftMenuItems{ get; set; }
public virtual List<Page> Pages { get; set; }
public Page ActivePage { get; set; }
public int ActivePageIndex { get; set; }
public Site()
{
NextPageOrder = 1;
MenuVariant = "top";
ColorTheme = "dark";
}
}
頁面類
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public virtual List<Row> Rows { get; set; }
public int SiteId { get; set; }
public virtual Site Site { get; set; }
public int Order { get; set; }
public int NextRowOrder { get; set; }
public Page()
{
Title = "title";
Rows = new List<Row>()
{
new Row()
};
}
首先,我假設您的網站和頁面具有某種關系。 當您嘗試從站點表中獲取數據時,您正在從頁面表中獲取數據,並且已在dbcontext查詢中包含了頁面。 因此,如果您看到在dbcontext中使用include,則表示站點和頁面之間已進行左外部聯接。
您可以在http://www.entityframeworktutorial.net/EntityFramework4.3/eager-loading-with-dbcontext.aspx上查看有關急切加載的更多信息 。 讓我知道它是否可以解決您的查詢。
在問題評論中查看解決方案,非常感謝Ivan Stoev。 問題出在實體構造函數中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.