3

我在同时使用 WCF 服务和实体模型时遇到了问题。我已经从我现有的数据库中创建了一个实体模型。这可以在下面显示;

在此处输入图像描述

在来自“实体对象代码生成器”的任何控制台应用程序中使用我的类时没有任何问题。

然后,我用下面的接口创建了 WCF 服务:

    [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();

}

但是,当我在服务类中实现这些方法并运行我的客户端应用程序时,我收到了类似的错误

在此处输入图像描述

我怎样才能摆脱这个问题?

问候, 凯马尔

4

1 回答 1

4

您的实体是否标有DataContract属性?你确定它们是可序列化的吗?

编辑:通过查看您的代码,您似乎正在直接使用您的实体。这不是一个好的做法,因为(即使您的代码正在运行)我认为您不需要额外的属性,例如 Entity Framework 自动生成的属性。

在这些情况下,您应该考虑使用 DTO(数据传输对象),这是一个Newspaper类可能如何的示例:

[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; }
}

然后为您服务:

public List<NewspaperDTO> GetNews()
{
    return entities.Newspapers.Select(a => new NewspaperDTO(a)).ToList();
}

PS 我注意到您的实体没有被处置(我的意思是在 WCF 服务内部)。您应该考虑在服务的每个方法中使用这样的模式:

public List<NewspaperDTO> GetNews()
{
    using (var entities = new MyEntities())
    {
        return entities.Newspapers.Select(a => new NewspaperDTO(a)).ToList();
    }
}
于 2011-08-23T12:58:55.503 回答