2014-02-09 4 views
2

Entity Framework, Web API를 함께 사용할 수 있습니까?Entity Framework 데이터베이스 (웹 API 포함)

응용 프로그램 구조 : AngularJS와와

  1. 웹 API 응용 프로그램
  2. 데이터 액세스 레이어 : 나는 모델로 DAL에서 엔티티를 사용하려면 내 웹 API 응용 프로그램에서 엔티티 프레임 워크

와.

웹 API 컨트롤러에서 반환되는 데이터는 JSON이어야합니다.

나는 항상이 같은 오류를 얻을 때 :

{ "$ ID가": "1", "메시지": "오류가 발생했습니다.", "ExceptionMessage"는 " 'ObjectContent 1' 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.ObjectQuery 1 .GetResults (Nullable 1 forMergeOption)\r\n at System.Data.Objects.ObjectQuery System.Collections.Generic.IEnumerable.GetEnumerator() System.Collections.Generic.List의 1..ctor(IEnumerable 컬렉션) System.Linq.Enumerable.ToList의 [TSource] (Newtonsoft.Json.Serialization.JsonArrayContract.CreateWrapper (Object list) \ Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue (JsonWriter 작성기, Object 값, JsonContract valueContract, JsonProperty 멤버, IEnumerable`1 소스) \ r \ JsonContainerContract containerContract, JsonProperty containerProperty) \ r \ n Newtonsoft.Json에서 .Serialization.JsonSerializerInternalWriter.Serialize (JsonWriter jsonWriter 오브젝트 값) Newtonsoft.Json.JsonSerializer.SerializeInternal (JsonWriter jsonWriter 오브젝트 값) \ R \ n Newtonsoft.Json.JsonSerializer.Serialize에서 (JsonWriter jsonWriter 오브젝트 가치 \ r에 \ 없음) \ r \ n System.Net.Http.Formatting.JsonMediaTypeFormatter. <> C_ DisplayClassd.b _C() \ r은 N System.Threading.Tasks.TaskHelpers.RunSynchronously (액션 액션, CancellationToken 토큰) "}}} 여기

내 컨트롤러입니다 \ (동일 코드는 경우에 노력하고 있습니다 나는 당신의 맥락에서 코드 순으로)

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; 
    } 
} 
} 
+0

은 모두 함께 사용할 수있다. 문제는 웹 API에 있습니다. 당신은 당신이 액세스하려고 한 컨트롤러를 추가 할 수 있습니까? – kubuntu

+2

DataContext가 삭제됩니다. using (var db = new AdvanceContext())를 다음으로 변경하십시오. var db = new AdvanceContext(); –

답변

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; } 
관련 문제