Track specific fields of a list of objects #725
Replies: 3 comments
-
Please provide a more detailed example of what might happen to the list. Also, what is the scope of the list, and what is your expected output? With that information, I can help you better. |
Beta Was this translation helpful? Give feedback.
-
For example: The output is let's say a list of video Games. I need to get a list of id's for those games so I know which ones a person read. I don't need the entire list object tracked, I just need the id's. I got the below code working. Is there a better way? `Audit.Core.Configuration.AddOnSavingAction( scope =>
|
Beta Was this translation helpful? Give feedback.
-
Do not use the "target" object if you only need to track an object's instantaneous state. Use the "target" object only when you need to track both the old and new values of an object—capturing its state at the beginning of the audit scope and its final state when the scope is disposed. In your case, you can use a Example:// Custom derived audit event that holds an extra property "List"
public class MyAuditEvent : AuditEvent
{
public MyAuditEvent(IList list)
{
List = list;
}
public IList List { get; set; }
} When creating an audit scope, you can pass an instance of the custom audit event: var myGames = new List<Game>
{
new Game { Id = 1, Name = "Game 1", Rating = 5 },
new Game { Id = 2, Name = "Game 2", Rating = 4 },
new Game { Id = 3, Name = "Game 3", Rating = 3 }
};
AuditScope.Create(c => c
.EventType("GetAll")
.AuditEvent(new MyAuditEvent(myGames))
.IsCreateAndSave()); Additionally, you can modify the Audit.Core.Configuration.AddOnSavingAction(scope =>
{
if (scope.Event is MyAuditEvent auditEvent)
{
var auditList = auditEvent.List
.Cast<object>()
.Select(item => new AuditListModel
{
Id = (int)item.GetType().GetProperty("Id")!.GetValue(item)!
})
.ToList();
auditEvent.List = auditList;
}
}); This is just one approach; similar functionality can be achieved in various ways. For example, you could avoid the OnSaving action and have the logic to create the list of only Ids in the public class MyAuditEvent : AuditEvent
{
public MyAuditEvent(IList list)
{
ListIds = list
.Cast<object>()
.Select(item => (int)item.GetType().GetProperty("Id")!.GetValue(item)!)
.ToList();
}
public List<int> ListIds { get; set; }
} |
Beta Was this translation helpful? Give feedback.
-
What is the best way to track a proper in a list of items, but you only want to record a specific field.
Example:
var myList = an list
myList contains
{
id: 1
title: "some title"
},
{
id: 2
title: "some title 2"
}
I only want to track the id's of all the objects in the list.
When I needed to do is see who requested all the items and what the id's of all the items are.
Beta Was this translation helpful? Give feedback.
All reactions