WCF Service - Serialize Linq Parameter

I have a simple class:

[DataContract] public class Book { [DataMember] public Int32 ID { get; set; } [DataMember] public Nullable<Int32> AuthorID { get; set; } } 

which is retrieved through the WCF service, for example:

 public class BookService : IBookService { IService _service; public BookService() { _service = new BookService(); } public IEnumerable<Book> GetBooks() { var Books = _service.GetBooks(); return Books; } } 

Now I want to extend this by adding an additional function that would allow the LINQ query to include additional properties in the Book class (not shown in the above example). The function for this (which works when turned on and invoked from an MVC application):

  public IEnumerable<Book> GetBooks(params Expression<Func<Book, object>>[] includes) { var Books = _service.GetBooks(Expression<Func<Book, object>>[]>(includes)); return Books; } 

However, when starting from the WCF service, this generates an error because it cannot be serialized:

System.ServiceModel.Description.DataContractSerializerOperationBehavior contract: http://tempuri.org/:IBookService ----> System.Runtime.Serialization.InvalidDataContractException: Type 'System.Linq.Expressions.Expression 1[System.Func 2 [Foo. Book, System.Object]] 'cannot be serialized. Consider labeling it with the DataContractAttribute attribute and labeling all of its elements that you want to serialize with the DataMemberAttribute attribute. If the type is a collection, consider labeling it with CollectionDataContractAttribute.

I added the DataContract / DataMember attributes to the class so that it can be serialized, however I'm not sure what I need to do to allow the parameterization of the function to be parameterized.

Anyone have any ideas on what I can do so that this feature can be used in the WCF service?

+5
source share
2 answers

Could this be related to using Expression ?:

Why are you using Expression <Func <T →> and not Func <T>?

0
source

A generic list, such as an array, is not Serializable, so you get an error. Modify your code to pass the list of fields you want to return to an object that can be serialized. When you pass parameters in an object that can be serialized, the function should work when in web services.

 [Data Contract] public class Field { [DataMember] public string FieldName {get; set;} } 

Then you can pass it to functions

 List<Fields> fieldList = new List<Field>(); fieldList.Add(new Field("Field1"); fieldList.Add(new Field("Field2"); _service.GetBooks(Expression<Func<Book, object>>[]>(fieldList)); 

** Not sure about the syntax of the last line, I didn’t work very much with expressions

0
source

Source: https://habr.com/ru/post/1275790/


All Articles