I try to create a timeline collection that contians multiple types. I have no problem to insert the type or read a specific type. But when i want a list of all types for a specific user, then i got problem.
public interface ITimelineItem
{
public string EventType { get; set; }
public string EventId { get; set; }
public Guid UserId { get; set; }
}
public class TimelineItemBase
{
public string EventType { get; set; }
public string EventId { get; set; }
public Guid UserId { get; set; }
public List<MediaInfo> Media { get; set; }
}
public class AlbumEvent : TimelineItemBase, ITimelineItem
{
public MediaAlbum Album { get; set; }
}
public class BirthdayEvent : TimelineItemBase, ITimelineItem
{
}
public class BlogPostEvent : TimelineItemBase, ITimelineItem
{
public BlogPost Post { get; set; }
}
public static class TimelineRepo
{
private static IMongoCollection<T> GetCollection<T>() where T : ITimelineItem
{
return Connection.Database.GetCollection<T>("Timeline");
}
public static async Task Add<T>(T data) where T : ITimelineItem
{
data.EventType = typeof(T).Name;
var coll = GetCollection<T>();
await coll.InsertOneAsync(data);
}
public static async Task<List<T>> GetEventsByUserId<T>(Guid userId) where T : ITimelineItem
{
return await GetCollection<T>().Find(p => p.UserId == userId).ToListAsync();
}
}
public class GenerateTimeline
{
public static async Task<List<ITimelineViewModel>> GetTimeline(Guid userId)
{
var items = await TimelineRepo.GetEventsByUserId<???>(userId);
foreach (var item in items)
{
if (item is BirthdayEvent be)
{
// do work
}
else if (item is BlogPostEvent bp)
{
// do work
}
else if (item is AlbumEvent ae)
{
// do work
ae.Album.Header
}
}
}
}
[HttpGet("/api/user/{userid}/timeline"), Authorize]
public async Task<List<ITimelineViewModel>> GetTimeline(Guid userId)
{
return await GenerateTimeline.GetTimeline(userId);
}
How can I get a list containing different types for a user? Or is this a bad way to create a timeline for users?