为什么我的WCF服务没有使用我的实体模型?

3
我在使用WCF服务和实体模型时遇到了问题。我已经从现有的数据库创建了一个实体模型,如下所示:

enter image description here

在任何来自“实体对象代码生成器”的控制台应用程序中使用我的类时都没有任何问题。
接下来,我创建了以下接口的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();

}

然而,当我在服务类中实现这些方法并运行我的客户端应用程序时,出现了一个错误,如下图所示。您该如何解决这个问题?问候,KEMAL
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();
}

顺便提一下,我注意到你的实体(指WCF服务中的实体)没有被释放。你应该在每个方法中考虑使用类似这样的模式:

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

正如您在我的第二个截图中所看到的,返回作者的GetAuthors方法运行良好,而返回报纸的GetNewspapers方法则无法正常工作。我发现,如果我从“实体模型自跟踪对象生成器”创建实体对象,则一切都正常。然而,这一次,当我尝试使用REST服务通过webHttpBinding发布我的服务时,即使我填充了ResponseFormat,它也不会将我的对象序列化/反序列化为JSON对象。顺便说一句,如果我想将其序列化/反序列化为XML,则它可以正常工作,但是实体对象仍应由“自跟踪对象生成器”生成。 - kkocabiyik
对于你的两个问题,我的回答是肯定的。顺便说一下。 - kkocabiyik
我有点难理解发生了什么。即使您已经发布了类图,我也不确定背景中正在发生什么。尝试链接一个压缩的解决方案给我,我会看一下 ;) - as-cii
1
我必须说,我只是在这里跳进来,因为我看不到图片(在工作中被阻止),我只是猜测。你的实体是否相互引用?例如,你是否有一个父级带有子级列表,引用父级?WCF 将尝试序列化它们,但由于无限递归而失败。我已经见过几次这种情况。 - Mike M.
1
有很多原因可能导致这个无法工作,不管怎样,考虑采用不同的方法是合理的。我的意思是,客户端需要知道像“EntityKey”或“EntityState”这样的属性吗? - as-cii

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接