[英]Entities are not serializing using DataContractSerializer
I am trying to serialize Entities in my project. 我正在尝试在项目中序列化实体。 I have a lot of them so i'm starting with just one at the moment.
我有很多,所以现在我只介绍一个。 The goal of my project is to create an audit trail with entity framework.
我项目的目标是使用实体框架创建审核跟踪。 When I break at audit.newvalue = doc.root.tostring() the root is null.
当我在audit.newvalue = doc.root.tostring()处中断时,根为null。 I've been trying to follow every tutorial or q/ai find related to doing this, but everytime i get null.
我一直在尝试遵循与此相关的每个教程或q / ai查找,但是每次我都为空。 Not sure what i'm missing here.
不知道我在这里想念的是什么。
[DataContract(IsReference=true)]
public class Client
{
[DataMember]
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[DataMember]
public bool Active { get; set; }
[DataMember]
[Required]
public string LastName { get; set; }
[DataMember]
public string MiddleName { get; set; }
[DataMember]
[Required]
public string FirstName { get; set; }
[DataMember]
[Required]
public DateTime BirthDate { get; set; }
}
private Audit.DBAudit AuditTrailFactory(ObjectStateEntry entry, string userName)
{
var oc = this as IObjectContextAdapter; ;
oc.ObjectContext.DetectChanges();
Audit.DBAudit audit = new Audit.DBAudit();
audit.TimeStamp = DateTime.Now;
audit.Entity = entry.EntitySet.Name;
audit.User = userName;
// set action type
switch (entry.State)
{
case System.Data.EntityState.Added:
audit.ActionType = ActionTypes.I.ToString();
break;
case System.Data.EntityState.Modified:
audit.ActionType = ActionTypes.U.ToString();
break;
case System.Data.EntityState.Deleted:
audit.ActionType = ActionTypes.D.ToString();
break;
default:
audit.ActionType = "F"; // fubar
break;
}
DataContractSerializer serializer = new DataContractSerializer(entry.Entity.GetType());
XDocument doc = new XDocument();
XmlWriter writer = doc.CreateWriter();
serializer.WriteObject(writer, entry.Entity);
audit.NewValue = doc.Root.ToString();
return audit;
}
[TestMethod]
public void CanCreateAudit()
{
FircrestModel.Client.Client client = new FircrestModel.Client.Client
{
FirstName = "billy",
LastName = "jones",
BirthDate = new DateTime(1970, 1, 1),
};
context.Clients.Add(client);
context.SaveChanges();
}
after using this implementation of the DataContractSerializer, I got an expected output. 使用DataContractSerializer的此实现后,我得到了预期的输出。 as i mentioned in a comment above, the client class is an abridged version.
正如我在上面的评论中提到的,客户端类是一个简化版本。 i'm going to slowly go through my client class uncommenting properties until i find the one that seems to have broken the serializer.
我将缓慢地浏览我的客户端类的注释属性,直到找到似乎破坏了序列化程序的属性为止。
How to use DataContractSerializer to create xml with tag names that match my known types 如何使用DataContractSerializer创建标记名称与我的已知类型匹配的xml
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.