My web service is:
[WebMethod]
public List<Activity> ActivityInf()
{
List<Activity> operationActivities = (List<Activity>)operationActivityCtrl.Result;
return operationActivities;
}
In fact when i changed List, i saw operationActivities. but while i was run it, i got some error.
Server Error in '/' Application.
Cannot serialize member Test.Core.Model.DS.Act.PCustomerList of type System.Collections.Generic.IList`1[[Test.Core.Model.DS.PCus, Test.Core.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] because it is an interface.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NotSupportedException: Cannot serialize member Test.Core.Model.DS.Act.PCustomerList of type System.Collections.Generic.IList`1[[Test.Core.Model.DS.PCus, Test.Core.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] because it is an interface.
Source Error:
An unhandled exception was generated during the execution开发者_StackOverflow社区 of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
From the exception it looks like your Activity object contains properties that are not serializable (an IList which is not serializable). Generally when you need to transfer NHibernate entities over WCF or web services you don't actually transfer the entity but instead use a DTO.
DTOs are even simpler objects than your entities containing only the information you need to pass rather than the whole NHibernate entity which can contain a complex object graph. These will also contain concrete implementations of Lists instead of IList. Basically they are serializable. There is much more information on this topic if you search for DTOs and NHibernate.
You likely have properties in the Activity object that are still attached to the NHibernate proxy. The quick way to avoid this would be to use Eager [Not.LazyLoad()] loading. If you're using Fluent NHibernate this looks like:
References<Activity>(x => x.ActivityType, "ActivityType_Id")
.Nullable()
.Column("ActivityType_Id")
.Not.LazyLoad()
.ForeignKey("Id");
I generally like to have a namespace in my model project for Dtos. Like MyCompany.MyModel.Entities (for NHibernate) and MyCompany.MyModel.Dtos (for stuff I need to serialize).
Then I use AutoMapper to convet a given Entity object to the respective Dto and serialize it, like:
var activityDto = Mapper.Map<Activity, Dtos.Activity>(activity);
return JsonSerializer.SerializeToString<Dtos.Activity>(activityDto);
精彩评论