Auditing a Table with EF Code first

强颜欢笑 提交于 2020-01-15 10:39:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!