Auditing table with EF code

I have a say Message class as shown below:

 public class Message { public int Id{get;set;} public string MessageText{get;set;} public int Sender{get;set;} public DateTime CreatedOn{get;set;} //EDIT:2 public virtual Message RepliedTo{get;set;} public virtual IList<Message> Replies{get;set;} public virtual IList<MessageStatusHistory> History{get;set;} //so on and so forth } 

Now I want to save the statuses of the Message object as what the user marked as read and when. I created the MessageStatusHistory class as:

 public class MessageStatusHistory { public int Id{get;set;} public string Status{get;set;} public DateTime StatusDate{get;set;} public int UserId{get;set;} public int MessageId{get;set;}//EDIT:2 public Message Message{get;set;} } 

I am confused about how to configure the mapping for the Message and MessageStatusHistory classes so that I can get the entire history for Message from the object itself.

Also, there will not be a record in the status history table until some user marks are read.

EDIT: 2 I configured the mapping for Message as follows:

 ToTable("Messages"); HasOptional(x => x.RepliedTo).WithMany(x => x.Replies) .Map(n => n.ToTable("Messages")); 

And to display the MessageStatusHistory :

 HasRequired(x => x.Message).WithMany(n => n.History) .HasForeignKey(x => x.MessageId) 

Now when I run the following tests:

 using (IKernel ker = new StandardKernel()) { ker.Rebind<IDbContext>().To<MessageDbContext>(); ker.Rebind<IRepository<Message>>().To<EFRepository<Message>>(); ker.Rebind<IRepository<MessageStatusHistory>>() .To<EFRepository<MessageStatusHistory>>(); var svc = ker.Get<MessageService>(); var message = svc.Create("hello world", 1, " user2@example.com "); var nn = svc.AddReplyToMessage(message, "Message 2", 1, " user2@example.com "); var nnn = svc.AddReplyToMessage(nn, "Message 3", 2, " user1@example.com "); var nhs = ker.Get<MessageStatusHistoryService>(); nhs.Create(message, Status.MarkedRead, 2, " user1@example.com "); nhs.Create(message, Status.MarkedRead, 1, " user2@example.com "); nhs.Create(nnn, Status.MarkedRead, 2, " user1@example.com "); nhs.Create(nn, Status.MarkedRead, 1, " user2@example.com "); nhs.Create(nn, Status.MarkedRead, 2, " user1@example.com "); } 

Lines that create state history objects reinsert Message objects :( I think this is due to the HasRequired(x=>x.Message) material in the mapping. But not sure. Please help resolve this.

+1
source share

All Articles