簡體   English   中英

通過Web Service返回的Entity Framework類的問題

[英]Issue with Entity Framework class being returned via Web Service

我已經實現了一個Web服務,我通過ajax調用它。
注意:我的實體是為實體框架代碼首先制作的。

我的ajax看起來如下:

$.ajax({
   type: "GET",
   url: "/MyProject/MyService.svc/GetEntity",
   data: "entityID=1",
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   success: AjaxSucceeded,
   error: function (msg, status, extra) {
      alert(status + " - " + extra);
   }
 });

AjaxSucceeded只是一個帶有數據變量的函數,我只是在控制台中記錄數據。

我的GetEntity函數目前看起來像這樣:

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public MyEntity GetEntity(int entityID)
{
    AccessObject accessObject = new AccessObject("MyConnectionString");

    MyEntity theEntity = accessObject.GetByID(entityID);

    return theEntity;
}

我已經用一個有目的地進行測試的類來測試它,它按預期工作(例如,我在Web服務中創建了一個非常簡單的MyEntity類,一些屬性,沒有其他方法等)。

當我返回我為代碼第一個實體框架所做的實體時,會出現問題。 它不起作用,多次調用Web服務函數,然后控制台中出現錯誤,指出“無法加載資源”,指的是我的服務功能。

供參考,這是我的實體:

[DataContract(IsReference=true)]
public class MyEntity
{
    #region Properties

    [Key]
    [DataMember]
    public int ID { get; set; }

    public bool SomeBoolean { get; set; }

    [StringLength(1000)]
    public string Description { get; set;}

    #endregion

    #region Relationships

    public virtual SomeOtherEntity OtherEntity { get; set; }

    #endregion

}

我只將ID設置為DataMember進行測試,但仍未成功。

有人能指出我正確的方向嗎? 我知道Web服務有效,因為其他功能可以工作,如果我設置了一個本地(在Web服務中)類,它將返回沒有問題。 所以我假設它與實體框架屬性有關? 我可能錯了,但這是我能想象到的。

感謝您的時間。

哦,作為參考,我的服務類具有以下屬性:

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  

問題只是實體並不是真正為序列化而構建的。 我的建議是創建一個DTO,將相關屬性映射到並通過線路傳遞,例如

public class EntityDto
{
    public int ID { get; set; }
    public string Description { get; set; }
    ...
}

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public EntityDto MyEntity(int entityId)
{
    AccessObject accessObject = new AccessObject("MyConnectionString");
    MyEntity theEntity = accessObject.GetByID(entityID);
    return new EntityDto()
    {
        ID = theEntity.ID,
        Description = theEntity.Description,
        ...
    };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM