Bil*_*mpf 4 rest wcf json entity-framework poco
我已经使用REST模板编写了一个WCF服务,该模板将defaultOutgoingResponseFormat设置为Json.在此之下,我使用Entity Framework和ObjectContext构建了一个简单的实体模型,以传递自定义POCO实体.
如果我传递单个实体,则系统按预期工作.如果我将子项添加到实体,则REST响应为空.在调试器中,实体填充正确,但服务本身根本不返回任何内容.
所以,例如,我有一个Trip.Get()方法.WCF代码如下所示:
[WebGet(UriTemplate = "{id}", ResponseFormat = WebMessageFormat.Json)]
public Model.Trip Get(string id)
{
Model.Trip fetchedTrip = null;
try
{
fetchedTrip = Library.Trip.Get(new Guid(id));
}
catch (Exception ex)
{
Debug.Write(ex.Message);
}
return fetchedTrip;
}
Run Code Online (Sandbox Code Playgroud)
Library.Trip.Get在工作版本中看起来像这样:
public static Model.Trip Get(Guid tripId)
{
using (Model.POCOTripContext context = new Model.POCOTripContext())
{
var tripEntity = context.Trips.FirstOrDefault(c => c.Id == tripId) ?? new Model.Trip();
return tripEntity;
}
}
Run Code Online (Sandbox Code Playgroud)
这将返回预期结果,如下所示:
{ "ArrivalDate": "/日期(1334203200000-0400)/", "DepartureDate": "/日期(1334721600000-0400)/", "ID": "d6413d96-fe1f-4b1c-ae7a-3bbf516cdc2f", "姓名" :"测试123","照片":null,"PlacesOfInterest":null,"WhereTo":"Orlando,FL"}
但是,如果我将库方法更改为添加到子项中,则REST服务将返回空值.没什么,虚无...
public static Model.Trip Get(Guid tripId)
{
using (Model.POCOTripContext context = new Model.POCOTripContext())
{
var tripEntity = context.Trips.Include("PlacesOfInterest").Include("Photos").Include("PlacesOfInterest.PoiAttributes").FirstOrDefault(c => c.Id == tripId) ?? new Model.Trip();
return tripEntity;
}
}
Run Code Online (Sandbox Code Playgroud)
调试器在return语句的WCF服务中显示实体已完全正确填充.
我确信我只是缺少一些神奇的属性,我希望以前能够帮助我的人能够帮助我!
根据你的小测试删除回溯跟踪导航属性,你有序列化到JSON的问题.默认序列化无法跟踪对象引用,因此当它开始序列化时,Trip它会跟随导航属性到感兴趣的点,并且在它们中首先找到引用Trip.因为它不跟踪引用,所以它遵循导航属性并再次序列化行程(并再次遵循其导航属性)=>无限循环.
您必须像在测试中一样删除后向跟踪导航属性,或者必须告诉序列化程序跟踪引用或从序列化中排除该属性(我不确定第一个选项在JSON的情况下会做什么).我猜你正在使用默认的WCF序列化,所以:
[DateContract(IsReference = true)]使用[DataMember]属性标记每个实体和每个序列化属性以开始跟踪引用.[IgnoreDataMember]属性标记跟踪导航属性以从序列化中排除属性| 归档时间: |
|
| 查看次数: |
1815 次 |
| 最近记录: |