我正在关注本教程http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-4
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using BookService.Models;
namespace BookService.Controllers
{
public class BooksController : ApiController
{
private BookServiceContext db = new BookServiceContext();
// GET: api/Books
public IQueryable<Book> GetBooks()
{
return db.Books;
// new code:
.Include(b => b.Author);
}
我说添加.Include(b => b.Author);
来执行急切加载。
并使用System.Data.Entity.Include
我已经这样做了,我还添加了Entityframwork和nuget,但我得到了
意外的令牌 无法解决'包含' 代码无法访问
我仍然错过了Etityframwork.dll,如果是的话,我该怎么做?
答案 0 :(得分:1)
如何阅读from related article of MSDN - Loading Related Entities
预先加载是查询一种类型实体的过程 还会将相关实体作为查询的一部分加载。渴望加载 通过使用Include方法实现。
using (var context = new BloggingContext())
{
// Load all blogs and related posts
var blogs1 = context.Blogs
.Include(b => b.Posts)
.ToList();
// Load one blogs and its related posts
var blog1 = context.Blogs
.Where(b => b.Name == "ADO.NET Blog")
.Include(b => b.Posts)
.FirstOrDefault();
// Load all blogs and related posts
// using a string to specify the relationship
var blogs2 = context.Blogs
.Include("Posts")
.ToList();
// Load one blog and its related posts
// using a string to specify the relationship
var blog2 = context.Blogs
.Where(b => b.Name == "ADO.NET Blog")
.Include("Posts")
.FirstOrDefault();
}
但你的代码有错字;你的;
太多了:
return db.Books.Include(b => b.Author);
问题在于:
return db.Books; <---