Reputation: 4406
I got a problem on using WCF service and Entity Model with together. I have created an Entity Model from my existing database. This can be shown below;
There isn't any problem while using my classes in any console applicaton coming from "Entity Object Code Generator".
Then, I created WCF Service with Interface Below:
[ServiceContract]
public interface IAuthorServices
{
[OperationContract]
[WebGet( UriTemplate="GetNews")]
List<Newspaper> GetNews();
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetAuthors")]
List<Author> GetAuthors();
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetAuthorTexts")]
List<AuthorText> GetAuthorTexts();
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetTodaysTexts")]
List<AuthorText> GetTodaysTexts();
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetExceptions")]
List<KoseYazilari.Exception> GetExceptions();
}
However when I implement these methods in a service class and run my client application, I got an error like
How can I get rid of this problem?
Regards, KEMAL
Upvotes: 3
Views: 3084
Reputation: 13019
Are your entities marked with a DataContract
attribute? Are you making sure that they are serializable?
EDIT: By looking at your code it seems that you are using your entities directly. This is not a good practice because (even if your code was working) I don't think you want extra properties like the ones that Entity Framework auto-generates.
In these case you should consider to use DTOs (Data Transfer Objects), this is an example of how Newspaper
class could be:
[DataContract]
public class NewspaperDTO
{
public NewspaperDTO(Newspaper newspaper)
{
this.Name = newspaper.Name;
this.Image = newspaper.Image;
this.Link = newspaper.Link;
this.Encoding = newspaper.Encoding;
}
[DataMember]
public string Name { get; set; }
[DataMember]
public string Image { get; set; }
[DataMember]
public string Link { get; set; }
[DataMember]
public string Encoding { get; set; }
}
And then in your service:
public List<NewspaperDTO> GetNews()
{
return entities.Newspapers.Select(a => new NewspaperDTO(a)).ToList();
}
P. S. I have noticed that your entities are not disposed (inside the WCF service I mean). You should consider using a pattern like this in every method of your service:
public List<NewspaperDTO> GetNews()
{
using (var entities = new MyEntities())
{
return entities.Newspapers.Select(a => new NewspaperDTO(a)).ToList();
}
}
Upvotes: 4