0

我正在尝试序列化项目中的实体。我有很多,所以我现在只从一个开始。我的项目的目标是使用实体框架创建审计跟踪。当我在 audit.newvalue = doc.root.tostring() 中断时,根为空。我一直在尝试遵循与执行此操作相关的每个教程或 q/ai 发现,但每次我得到空值。不知道我在这里缺少什么。

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

1 回答 1

0

在使用 DataContractSerializer 的这个实现之后,我得到了预期的输出。正如我在上面的评论中提到的,客户端类是一个精简版。我将慢慢检查我的客户端类取消注释属性,直到找到似乎破坏了序列化程序的属性。

如何使用 DataContractSerializer 创建标记名称与我已知类型匹配的 xml

于 2012-08-31T17:29:35.440 回答