2
我正在使用WCF WebAPI創建REST服務和EF4。而返回其具有NavigationProperty一個對象(POCO類的),我得到以下序列化異常:返回具有導航對象集合的對象時的序列化問題
無法序列類型System.Collections.Generic.ICollection`1 [[模型的構件Models.Customer.Orders。 Order,Models,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]],因爲它是一個接口。
以下是POCO類
[Serializable]
[DataContract(IsReference = true)]
[KnownType(typeof(Order))]
public partial class Customer
{
#region Primitive Properties
[DataMember]
public virtual int CustomerID { get; set; }
[DataMember]
public virtual string CustomerCode { get; set; }
[DataMember]
public virtual string Description { get; set; }
[DataMember]
public virtual string Comments { get; set; }
[DataMember]
public virtual bool DeleteFlag { get; set; }
[DataMember]
public virtual byte[] RowVersion { get; set; }
#endregion
#region Navigation Properties
[DataMember]
public virtual ICollection<Order> Orders
{
get
{
if (_order == null)
{
var newCollection = new FixupCollection<Order>();
newCollection.CollectionChanged += FixupOrders;
_order = newCollection;
}
return _order;
}
set
{
if (!ReferenceEquals(_order, value))
{
var previousValue = _order as FixupCollection<Order>;
if (previousValue != null)
{
previousValue.CollectionChanged -= FixupOrders;
}
_order = value;
var newValue = value as FixupCollection<Order>;
if (newValue != null)
{
newValue.CollectionChanged += FixupOrders;
}
}
}
}
private ICollection<Order> _order;
#endregion
#region Association Fixup
private void FixupOrders(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (Order item in e.NewItems)
{
item.Customer = this;
}
}
if (e.OldItems != null)
{
foreach (Order item in e.OldItems)
{
if (ReferenceEquals(item.Customer, this))
{
item.Customer = null;
}
}
}
}
#endregion
}
服務的方法如下:
[WebGet(UriTemplate = "Customer",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml)]
public List<Customer> Get()
{
CustEntities context = new CustEntities();
return context.Customer.Include("Orders").ToList();
}
在上述方面的任何幫助,是非常可觀的。
感謝
我們正在使用EF T4模板創建POCO類。我們不想改變T4模板。是否有任何解決方法實現上述。 – SKumars 2011-12-25 12:52:52
你有沒有試過在你的客戶類中加入[KnownType(typeof(FixupCollection))]]? – 2011-12-27 23:47:08