Пытаюсь составить бизнес-логику для простого блога.
Как организовать возможность оценивать статью для всех пользователей?
public class Article : Content
{
protected internal Article(User contentOwner, string name, string text)
:base(contentOwner, ContentTypes.Article, name)
{
if (text.Length <= 0)
throw new ArgumentOutOfRangeException(nameof(text));
Text = text;
}
public Article(long id, User contentOwner, string name, string text, IEnumerable<Voting> votings)
: base(id, contentOwner, ContentTypes.Article, name, votings)
{
if (text.Length <= 0)
throw new ArgumentOutOfRangeException(nameof(text));
Text = text;
}
public string Text { get; set; }
}
public abstract class Content : IEntity
{
private readonly ISet<Voting> votings = new HashSet<Voting>();
internal Content(User contentOwner, ContentTypes type, string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Value cannot be null or whitespace.", nameof(name));
if (contentOwner == null)
throw new ArgumentNullException(nameof(contentOwner));
ContentOwner = contentOwner;
Type = type;
Name = name;
AverageRating = 0;
}
public Content(long id, User contentOwner, ContentTypes type, string name, IEnumerable<Voting> votings)
:this(contentOwner, type, name)
{
Id = id;
var votedList = votings.Select(v => v.User).ToList();
var ratingList = votings.Select(v => v.Rating).ToList();
AverageRating = GetAverageRating(ratingList);
}
public long Id { get; set; }
public User ContentOwner { get; init; }
public ContentTypes Type { get; init; }
public string Name { get; init; }
public double AverageRating;
private double GetAverageRating(IEnumerable<int> ratingList)
{
return Math.Round(ratingList.Average(), 1, MidpointRounding.AwayFromZero);
}
private void Vote(User user, int rating, List<User> votedList)
{
if (user == null)
throw new ArgumentNullException(nameof(user));
if (rating <= 0 || rating > 5)
throw new ArgumentOutOfRangeException(nameof(rating));
if ( !votedList.Contains(user) )
votings.Add(new Voting(user, rating));
else
throw new ArgumentException("User cannot vote again!", nameof(user.Email));
}
public class Voting : IValueObjectWithId
{
protected internal Voting(User user, int rating)
{
User = user;
Rating = rating;
}
public Voting(long id, User user, int rating)
: this(user, rating)
{
Id = id;
}
public long Id { get; set; }
public User User { get; init; }
public int Rating { get; init; }
}