【问题标题】:Entity Framework Database first with Web API实体框架数据库首先使用 Web API
【发布时间】:2014-02-09 23:27:57
【问题描述】:

是否可以同时使用Entity Framework、Web API?

应用结构:

  1. 使用 AngularJS 的 Web API 应用程序
  2. 数据访问层:使用实体框架

在我的 Web API 应用程序中,我想使用 DAL 中的实体作为模型。

从 Web API 控制器返回的数据应该是 JSON。

当我尝试时,总是会出现这样的错误:

{"$id":"1","Message":"发生错误。","ExceptionMessage":"'ObjectContent1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"$id":"2","Message":"An error has occurred.","ExceptionMessage":"Error while copying content to a stream.","ExceptionType":"System.Net.Http.HttpRequestException","StackTrace":null,"InnerException":{"$id":"3","Message":"An error has occurred.","ExceptionMessage":"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.","ExceptionType":"System.ObjectDisposedException","StackTrace":" at System.Data.Objects.ObjectContext.EnsureConnection()\r\n at System.Data.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)\r\n at System.Data.Objects.ObjectQuery1.System.Collections. Generic.IEnumerable.GetEnumerator()\r\n 在 System.Collections.Generic.List1..ctor(IEnumerable1 集合)\r\n 在 System.Linq.Enumerable.ToList[TSource](IEnumerable`1 源)\r\n在 Newtonsoft.Json.Serialization.JsonArrayContract.CreateWrapper(对象列表)\r\n 在 Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\ n 在 Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, 对象值)\r\n 在 Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, 对象值)\r\n 在 Newtonsoft.Json.JsonSerializer.Serialize( JsonWriter jsonWriter,对象值)\r\n 在 System.Net.Http.Formatting.JsonMediaTypeFormatter。 c_DisplayClassd.b_c()\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)"}}}

这是我的控制器(当我使用 Code First 时,同样的代码在工作)

public class TodoController : ApiController
{
  // GET api/Todo
  public IEnumerable<Todo> GetTodoItems(string q = null, string sort = null, 
       bool desc = false, int? limit = null, int offset = 0)
 {
   using (var db = new AdvanceContext())
   {
     var list = ((IObjectContextAdapter)db).ObjectContext.CreateObjectSet<Todo>();

     IQueryable<Todo> items = string.IsNullOrEmpty(sort)
              ? list.OrderBy(o => o.Priority)
              : list.OrderBy(String.Format("it.{0} {1}", sort, desc ? "DESC" : "ASC"));

     if (!string.IsNullOrEmpty(q) && q != "undefined")
        items = items.Where(t => t.Description.Contains(q));

     if (offset > 0)
        items = items.Skip(offset);

     if (limit.HasValue)
        items = items.Take(limit.Value);

      return items;
  }
 }
}

【问题讨论】:

  • 两者可以一起使用。问题出在您的 Web API 上。您可以添加您尝试访问的控制器吗?
  • 您的 DataContext 正在被处理。将 using (var db = new AdvanceContext()) 更改为: var db = new AdvanceContext();

标签: json entity-framework angularjs


【解决方案1】:

在您的上下文中添加以下行:

this.Configuration.LazyLoadingEnabled = true;
this.Configuration.ProxyCreationEnabled = false;

示例:

public partial class Dbname : DbContext
{
    public Dbname()
        : base("name=Dbname")
    {
        this.Configuration.LazyLoadingEnabled = true;
        this.Configuration.ProxyCreationEnabled = false;
    }

    public virtual DbSet<dtproperty> dtproperties { get; set; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    相关资源
    最近更新 更多