2017-03-09 78 views
0

在Windows 10 UWP應用程序,我使用的是實體框架的核心1.1本地SQLite數據庫和它的正常工作,現在,除了這一點:的Windows 10 UWP - 實體核心SQLite的:包括查詢錯誤

我試圖使用簡單的linq查詢將相關對象包含到我的用戶對象中。我測試了一些查詢,但包含方法和選擇限制的lambda表達式不起作用。

代碼示例:

public async Task<IUser> GetAsync(Guid id) 
{ 
    // Working, but useless 
    var user = await this.DbSet.Include(u => u.ProfileNavigation).FirstOrDefaultAsync(); 

    // Returns null 
    var user1 = await this.DbSet.Include(u => u.ProfileNavigation).FirstOrDefaultAsync(u => u.IdGuid == id); 

    // Returns null 
    var user2 = await this.DbSet.Where(u => u.IdGuid == id).Include(u => u.ProfileNavigation).FirstOrDefaultAsync(); 

    // Returns null linked object 
    User user3 = await this.DbSet.SingleOrDefaultAsync(u => u.IdGuid == id); 
    await this.Context.Entry(user3).Reference(p => p.ProfileNavigation).LoadAsync(); 

    // Result valid but painfull 
    User res = await (from u in this.DbSet 
         join p in this.Context.Set<Profile>() on u.ProfileGuid equals p.IdGuid 
         where u.IdGuid == id 
         select new User 
         { 
          Id = u.Id, 
          ProfileId = u.ProfileId, 
          ManagerUserId = u.ManagerUserId, 
          RegionId = u.RegionId, 
          Number = u.Number, 
          Password = u.Password, 
          FirstName = u.FirstName, 
          LastName = u.LastName, 
          Email = u.Email, 
          HideOnBoardAppConstr = u.HideOnBoardAppConstr, 
          ModifiedByUserId = u.ModifiedByUserId, 
          ProfileNavigation = p 
         }).FirstOrDefaultAsync(); 

    return res; 
} 

有誰有這個問題,並解決它?

在此先感謝。

回答

0

有一個關於create Database by the Entity Framework的官方文檔。

在本演練中,您將構建一個通用Windows平臺(UWP)應用程序,該應用程序使用實體框架對本地SQLite數據庫執行基本數據訪問。

您應該能夠檢查包含BlogPost類的BloggingContext類是否爲示例。

還有一個文件Entity Framework Loading Related Entities

緊急加載是一種過程,即查詢一種類型的實體也會將相關實體加載爲查詢的一部分。通過使用Include方法可以實現預加載。例如,下面的查詢將加載博客和與每個博客相關的所有帖子。

例如:

的BloggingContext類:

public class BloggingContext : DbContext 
{ 
    public DbSet<Blog> Blogs { get; set; } 
    public DbSet<Post> Posts { get; set; } 

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
    { 
     optionsBuilder.UseSqlite("Data Source=blogging.db"); 
    } 
} 

public class Blog 
{ 
    public int BlogId { get; set; } 
    public string Url { get; set; } 

    public List<Post> Posts { get; set; } 
} 

public class Post 
{ 
    public int PostId { get; set; } 
    public string Title { get; set; } 
    public string Content { get; set; } 

    public int BlogId { get; set; } 
    public Blog Blog { get; set; } 
} 

的包括查詢代碼:

using (var db = new BloggingContext()) 
{ 
    var blogs1 = db.Blogs.Include(b => b.Posts).ToList(); 
} 
0

此問題是部分地通過使用數據的基礎上下文實例爲每個解決請求。問題與上下文的依賴注入有關(我嘗試過使用SimpleIoc和Microsoft.Extensions.DependencyInjection),但它仍然讓我感到困惑。

歡迎任何評論。