【发布时间】:2014-05-28 15:12:03
【问题描述】:
在尝试序列化时,编译器会抛出一个错误,指出由于 ICollection<ChildrenClass> 属性,它无法序列化我的 EF 对象。
有没有办法在没有子类的情况下序列化 EF 对象?
【问题讨论】:
标签: entity-framework c#-4.0 xml-serialization
在尝试序列化时,编译器会抛出一个错误,指出由于 ICollection<ChildrenClass> 属性,它无法序列化我的 EF 对象。
有没有办法在没有子类的情况下序列化 EF 对象?
【问题讨论】:
标签: entity-framework c#-4.0 xml-serialization
你应该在你的 poco 模型上使用 AutoMapper 和 JsonIgnore 属性。
EF 类:
public class Customer
{
public int ID { get; set; }
public ICollection<ChildrenClass> MyChildren { get; set; }
}
POCO 模型:
public class CustomerModel
{
public int ID { get; set; }
[JsonIgnore]
public ICollection<ChildrenClass> MyChildren { get; set; }
}
自动映射器:
var customer = customerService.GetByID(1);
Mapper.CreateMap<Customer, CustomerModel>()
.ForMember(c => c.MyChildren, o => o.Ignore())
var customerModel = Mapper.Map<CustomerModel>(customer);
var json = JsonConvert.Serialize(customerModel);
或者你不能在你的模型类中包含 MyChildren 属性。
您也可以使用 MetaData 类标记 EF 模型,但我还没有尝试过:
[MetadataType(typeof(CustomerMetadata))]
public partial class Customer
{
internal class CustomerMetadata
{
[JsonIgnore]
public ICollection<ChildrenClass> MyChildren { get; set; }
}
}
【讨论】: