我正在寻找这个问题,但却找不到我需要的东西。我需要在Web API中使用Entity Framework模型来获取XML请求和响应。
我有两个有一对多关系的课程:
[Serializable]
[DataContract(Name = "shepherd")]
[KnownTypeAttribute(typeof(Sheep))]
public partial class Shepherd
{
public Shepherd()
{
this.Sheep = new HashSet<Sheep>();
}
[DataMember(Name = "shepherdId")]
//[XmlElement("shepherdId")]
public int Id { get; set; }
[DataMember(Name = "name")]
//[XmlElement("name")]
public string Name { get; set; }
[DataMember(Name = "isDeleted")]
//[XmlElement("IsDeleted")]
public Nullable<bool> IsDeleted { get; set; }
[DataMember(Name = "sheeps")]
//[XmlArray("sheeps"), XmlArrayItem("sheep")]
public virtual ICollection<Sheep> Sheep { get; set; }
}
这是第二堂课:
[DataContract(Name = "sheep")]
[KnownType(typeof(Shepherd))]
public partial class Sheep
{
[DataMember(Name = "id")]
//[XmlElement("id")]
public int Id { get; set; }
[DataMember(Name = "colour")]
// [XmlElement("colour")]
public string Colour { get; set; }
[DataMember(Name = "createdon")]
//[XmlElement("CreatedOn")]
public Nullable<System.DateTime> CreatedOn { get; set; }
public int Shepherd { get; set; }
[IgnoreDataMember]
public virtual Shepherd Shepherd1 { get; set; }
}
我总是得到这个错误:
&#39; ObjectContent`1&#39;类型无法序列化内容类型&#39; application / xml的响应正文;字符集= UTF-8&#39 ;.
System.InvalidOperationException键入&#39; System.Data.Entity.DynamicProxies.Shepherd_EF797FA5FAF7ACF0AF313B6DFF83AF6E5F2EE1AD57BC457F9C10E73BA5DEEFE6&#39;数据合同名称&#39; Shepherd_EF797FA5FAF7ACF0AF313B6DFF83AF6E5F2EE1AD57BC457F9C10E73BA5DEEFE6:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies&#39;不是预期的。考虑使用DataContractResolver或将任何静态未知的类型添加到已知类型列表中 - 例如,使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表中。
我只需要获取XML而不是Json