我的模型中有一个圆形对象图,但这是不可避免的。
根据本文中给出的建议,我对所有成员都使用了DataContractAttribute
and 设置。IsReference = true
我还提供了DataMemberAttribute
我想要序列化的所有属性。
为了确保序列化程序不再遇到任何问题,我只选择不序列化导航属性。
但是,我的 catch 块中仍然遇到异常。异常详情如下:
_innerException: {"Type
'System.Data.Entity.DynamicProxies.Author_615FB9F8BB22B55A7CA168DA5ED29EC6A0B59F62FD79D1346045351BE2F163A4' with data contract name
'Author_615FB9F8BB22B55A7CA168DA5ED29EC6A0B59F62FD79D1346045351BE2F163A4:
http://schemas.datacontract
.org/2004/07/System.Data.Entity.DynamicProxies' is not expected.
Consider using a
DataContractResolver or add any types not known statically to
the list of known types - for
example, by using the KnownTypeAttribute attribute or by adding them
to the list of known types
passed to DataContractSerializer."}
我可以但不希望:
1) 禁用代理创建。我可以仅仅为了序列化而删除代理创建,我可能会这样做。但我也想了解为什么我仍然会收到异常以及我能做些什么。
2)删除循环引用。原因:这些类型的引用在 Entity Framework 生成的模型中非常常见。如果我要做一个模型中有 800 - 1000 个类的大型项目,那么通过删除循环引用来实现它是一场噩梦。
我在下面描述了这个小尖峰解决方案的架构元素。
数据库模式
Id AuthorName
-------------------------------
1 Charles Dickens
2 Charles Petzold
3 Charles Darwin
4 Charles Chaplin
5 Leo Tolstoy
6 Fydor Dostoevsky
7 Ayn Rand
8 Napolean Hill
9 Claude M. Bristol
10 Edward Dwight Easty
11 O. Henry
12 William Shakespeare
13 Juwal Lowy
14 Jeffrey Richter
15 Chris Sells
16 Don Box
17 Steven Pinker
18 Jim Rohn
19 George Eliot
20 Sathyaish Chakravarthy
Id Title AuthorId
----------- -------------------------------------------------- -----------
1 Nicholas Nickleby 1
Id BookId Review
----------- ---------------------------------------------------------------
1 1 How do I know? I haven't read it.
模型
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace BookReviewsModel
{
[DataContract(IsReference = true)]
public partial class Author
{
[DataMember]
public virtual int Id { get; set; }
[DataMember]
public virtual string AuthorName { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
}
namespace BookReviewsModel
{
[DataContract(IsReference = true)]
public partial class Book
{
[DataMember]
public virtual int Id { get; set; }
[DataMember]
public virtual string Title { get; set; }
[DataMember]
public virtual int AuthorId { get; set; }
public virtual Author Author { get; set; }
public virtual ICollection<BookReview> BookReviews { get; set; }
}
}
namespace BookReviewsModel
{
[DataContract(IsReference = true)]
public partial class BookReview
{
[DataMember]
public virtual int Id { get; set; }
[DataMember]
public virtual int BookId { get; set; }
[DataMember]
[AllowHtml]
public virtual string Review { get; set; }
public virtual Book Book { get; set; }
}
}
控制器代码
namespace BookReviews.Controllers
{
public class AuthorController : ApiController
{
[HttpGet]
public IEnumerable<Author> Index()
{
try
{
using (var context = new BookReviewEntities())
{
var authors = context.Authors.ToList();
var str = Serialize(new XmlMediaTypeFormatter(), authors);
System.Diagnostics.Debugger.Break();
System.Diagnostics.Debug.Print(str);
return authors;
}
}
catch (Exception ex)
{
var responseMessage = new HttpResponseMessage
{
Content = new StringContent("Couldn't retreive the list of authors."),
ReasonPhrase = ex.Message.Replace('\n', ' ')
};
throw new HttpResponseException(responseMessage);
}
}
string Serialize<T>(MediaTypeFormatter formatter, T value)
{
Stream stream = new MemoryStream();
var content = new StreamContent(stream);
formatter.WriteToStreamAsync(typeof(T), value, stream, content, null).Wait();
stream.Position = 0;
return content.ReadAsStringAsync().Result;
}
}
}