使用Entity Framework的数据库优先模式与Web API。

3
可以将Entity Framework和Web API一起使用吗?
应用程序结构:
1.带有AngularJS的Web API应用程序 2.数据访问层:使用Entity Framework
在我的Web API应用程序中,我想要使用DAL中的实体作为模型。
从Web API控制器返回的数据应该是JSON格式。
当我尝试时,总是会出现以下错误:
{"$id":"1","Message":"An error has occurred.","ExceptionMessage":"The '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 at System.Collections.Generic.List1..ctor(IEnumerable1 collection)\r\n at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\r\n at Newtonsoft.Json.Serialization.JsonArrayContract.CreateWrapper(Object list)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value)\r\n at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)\r\n at 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上。你能添加你想要访问的控制器吗? - kubuntu
2
您的DataContext正在被释放。 将using (var db = new AdvanceContext())更改为: var db = new AdvanceContext(); - Larry Flewwelling
1个回答

0
在您的上下文中添加以下行:
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; }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接