我在同时使用 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();
}
然而,当我在服务类中实现这些方法并运行我的客户端应用程序时,我收到了类似的错误
我怎样才能摆脱这个问题?
问候,
凯玛
您的实体是否标有DataContract
属性?您确定它们是可序列化的吗?
EDIT:通过查看您的代码,您似乎正在直接使用您的实体。这不是一个好的做法,因为(即使您的代码正常工作)我认为您不需要额外的属性,例如实体框架自动生成的属性。
在这些情况下,您应该考虑使用 DTO(数据传输对象),这是一个如何使用 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();
}
P.S.我注意到您的实体没有被处置(我的意思是在WCF服务内)。您应该考虑在服务的每个方法中使用这样的模式:
public List<NewspaperDTO> GetNews()
{
using (var entities = new MyEntities())
{
return entities.Newspapers.Select(a => new NewspaperDTO(a)).ToList();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)