Web api扩展错误'object'不包含'Include'的定义

时间:2013-08-04 20:49:45

标签: entity-framework asp.net-web-api

这是我的模特:

练习:

 public class Exercise
    {


        public int ExerciseId { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }
}

肌肉:

public class Muscle
    {


        public int MuscleId { get; set; }

        public string Name { get; set; }
}

ExerciseAndMuscles

公共课练习和音乐     {         #region属性

    public int Id { get; set; }

    //each exercise hits muslce by some percentage
    public int PercentageByWhichMuscleIsHit { get; set; }

    #endregion

    #region Navigational properties

    public int MuscleId { get; set; }
    public virtual Muscle Muscle { get; set; }


    public int ExerciseId { get; set; }
    public virtual Exercise Exercise { get; set; }

    #endregion
}

这是FluentApi配置:

modelBuilder.Entity<ExercisesAndMuscles>()
                .HasRequired(e => e.Exercise)
                .WithMany()
                .HasForeignKey(e => e.ExerciseId)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<ExercisesAndMuscles>()
                .HasRequired(m => m.Muscle)
                .WithMany()
                .HasForeignKey(m => m.MuscleId)
                .WillCascadeOnDelete(false);

我在TestDatabaseContext中添加了这两行

Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;

这是我的WebApi

public class ExerciseAndMuscleController : ApiController
    {
        readonly TestDatabaseContext _databaseContext = new TestDatabaseContext ();
        // GET api/<controller>
        public IQueryable<ExercisesAndMuscles> Get()
        {
            return _databaseContext.ExercisesAndMuscleses.Include( m => m.Exercise).AsQueryable();
        }
}

当我尝试这样查询时:

http://localhost:23758/api/ExerciseAndMuscle?$expand=Exercise

我收到这些错误:

{"$id":"1","$type":"System.Web.Http.HttpError, System.Web.Http","Message":"An error has occurred.","ExceptionMessage":"'object' does not contain a definition for 'Include'","ExceptionType":"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException","StackTrace":"   at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>d__b.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()"}

没有包含和启用延迟加载的错误是相同的。

1 个答案:

答案 0 :(得分:2)

制作这样的方法:

[Queryable(AllowedQueryOptions= AllowedQueryOptions.Supported | AllowedQueryOptions.Expand)]
public IQueryable<ExercisesAndMuscles> Get()
{
        return _databaseContext.ExercisesAndMuscleses;
}

Web API应该能够翻译扩展,当然Web API仅支持在每晚构建中扩展。