我正在尝试序列化项目中的实体。我有很多,所以我现在只从一个开始。我的项目的目标是使用实体框架创建审计跟踪。当我在 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();
}