问题
I have a class say Message
like following:
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 keep statuses of the Message object like what user marked it as read and when. I created a class MessageStatusHistory
like:
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 as to how I should setup the mapping for Message
and MessageStatusHistory
classes so that I can get all the history for a Message
from the object itself.
Also a status history table will not have an entry till some user marks it read.
EDIT:2 I configured mapping for Message
as follows:
ToTable("Messages");
HasOptional(x => x.RepliedTo).WithMany(x => x.Replies)
.Map(n => n.ToTable("Messages"));
And for MessageStatusHistory
mapping is:
HasRequired(x => x.Message).WithMany(n => n.History)
.HasForeignKey(x => x.MessageId)
Now when I run 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");
}
The lines that create status history objects are re-inserting Message
objects :( I think it is because of HasRequired(x=>x.Message)
stuff in mapping. But not sure. Please help to resolve this.
来源:https://stackoverflow.com/questions/11168505/auditing-a-table-with-ef-code-first