实体未使用DataContractSerializer进行序列化

时间:2012-08-31 02:06:27

标签: c# entity-framework xml-serialization datacontractserializer

我正在尝试序列化项目中的实体。我有很多,所以我现在开始只有一个。我的项目的目标是使用实体框架创建审计跟踪。当我在audit.newvalue = doc.root.tostring()中断时,root为null。我一直在尝试按照每个教程或q / a我发现与此相关,但每次我得到null。不知道我在这里失踪了什么。

[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();
    }

1 个答案:

答案 0 :(得分:0)

使用DataContractSerializer的这个实现后,我得到了一个预期的输出。正如我在上面的评论中提到的,客户端类是一个删节版本。我将慢慢浏览我的客户端类,取消注释属性,直到我找到一个似乎已经破坏序列化器的那个。

How to use DataContractSerializer to create xml with tag names that match my known types