Just wondering your opinion on how I should model my documents for this scenario.
At the moment I have what seems a complex MultiMap index which is pulling in counters / stats from several other document collections, on my dev machine it's returning a small subset of test data in under 80ms (which i'm happy with).
What is the performance going to be like when this goes on my production server, on average each mix will receive around 500 plays per week, 200 downloads per week and a handful of likes, favourites and comments. I will be displaying 20-25 mixes per page.
Would you keep this design, or would it be better to denormalize my counters and store them on the Audio document, using the index would be alot less work as long as it will perform ok?
public class AudioWithCounters : AbstractMultiMapIndexCreationTask<AudioWithCounters.AudioViewModel>
{
public class AudioViewModel
{
public string Id { get; set; }
public string ArtistName { get; set; }
public string Name { get; set; }
public int TotalComments { get; set; }
public int TotalDownloads { get; set; }
public int TotalPlays { get; set; }
public int TotalLikes { get; set; }
public int TotalFavourites { get; set; }
public int WeeksComments { get; set; }
public int WeeksDownloads { get; set; }
public int WeeksPlays { get; set; }
public int WeeksLikes { get; set; }
public int WeeksFavourites { get; set; }
}
public AudioWithCounters()
{
AddMap<Audio>(audios => from audio in audios
select new
{
Id = audio.Id,
ArtistName = audio.ArtistName,
Name = audio.Name,
TotalDownloads = 0,
TotalComments = audio.CommentsCount,
TotalPlays = 0,
TotalLikes = 0,
TotalFavourites = 0,
WeeksDownloads = 0,
WeeksPlays = 0,
WeeksComments = 0,
WeeksLikes = 0,
WeeksFavourites = 0
});
AddMap<AudioComments>(comments => from audioComment in comments
from comment in audioComment.Comments
where comment.CreatedAt >= DateTimeOffset.Now.AddDays(-7)
select new
{
Id = audioComment.Audio.Id,
ArtistName = (string)null,
Name = (string)null,
TotalDownloads = 0,
TotalComments = 0,
TotalPlays = 0,
TotalLikes = 0,
TotalFavourites = 0,
WeeksDownloads = 0,
WeeksPlays = 0,
WeeksComments = 1,
WeeksLikes = 0,
WeeksFavourites = 0
});
AddMap<AudioCounter>(counters => from counter in counters
where counter.Type == Core.Enums.Audio.AudioCounterType.Download
select new
{
Id = counter.AudioId,
ArtistName = (string)null,
Name = (string)null,
TotalDownloads = 1,
TotalComments = 0,
TotalPlays = 0,
TotalLikes = 0,
TotalFavourites = 0,
WeeksDownloads = 0,
WeeksPlays = 0,
WeeksComments = 0,
WeeksLikes = 0,
WeeksFavourites = 0
});
AddMap<AudioCounter>(counters => from counter in counters
where counter.Type == Core.Enums.Audio.AudioCounterType.Play
select new
{
Id = counter.AudioId,
ArtistName = (string)null,
Name = (string)null,
TotalDownloads = 0,
TotalPlays = 1,
TotalComments = 0,
TotalLikes = 0,
TotalFavourites = 0,
WeeksDownloads = 0,
WeeksPlays = 0,
WeeksComments = 0,
WeeksLikes = 0,
WeeksFavourites = 0
});
AddMap<AudioCounter>(counters => from counter in counters
where counter.Type == Core.Enums.Audio.AudioCounterType.Download
where counter.DateTime >= DateTimeOffset.Now.AddDays(-7)
select new
{
Id = counter.AudioId,
ArtistName = (string)null,
Name = (string)null,
TotalDownloads = 0,
TotalPlays = 0,
TotalComments = 0,
TotalLikes = 0,
TotalFavourites = 0,
WeeksDownloads = 1,
WeeksPlays = 0,
WeeksComments = 0,
WeeksLikes = 0,
WeeksFavourites = 0
});
AddMap<Like>(likes => from like in likes
select new
{
Id = like.AudioId,
ArtistName = (string)null,
Name = (string)null,
TotalDownloads = 0,
TotalPlays = 0,
TotalComments = 0,
TotalLikes = 1,
TotalFavourites = 0,
WeeksDownloads = 0,
WeeksPlays = 0,
WeeksComments = 0,
WeeksLikes = 0,
WeeksFavourites = 0
});
AddMap<Favourite>(favs => from fav in favs
select new
{
Id = fav.AudioId,
ArtistName = (string)null,
Name = (string)null,
TotalDownloads = 0,
TotalPlays = 0,
TotalComments = 0,
TotalLikes = 0,
TotalFavourites = 1,
WeeksDownloads = 0,
WeeksPlays = 0,
WeeksComments = 0,
WeeksLikes = 0,
WeeksFavourites = 0
});
AddMap<AudioCounter>(counters => from counter in counters
where counter.Type == Core.Enums.Audio.AudioCounterType.Play
where counter.DateTime >= DateTimeOffset.Now.AddDays(-7)
select new
{
Id = counter.AudioId,
ArtistName = (string)null,
Name = (string)null,
TotalDownloads = 0,
TotalPlays = 0,
TotalComments = 0,
TotalLikes = 0,
TotalFavourites = 0,
WeeksDownloads = 1,
WeeksPlays = 0,
WeeksComments = 0,
WeeksLikes = 0,
WeeksFavourites = 0
});
AddMap<Like>(likes => from like in likes
where like.DateCreated >= DateTimeOffset.Now.AddDays(-7)
select new
{
Id = like.AudioId,
ArtistName = (string)null,
Name = (string)null,
TotalDownloads = 0,
TotalPlays = 0,
TotalComments = 0,
TotalLikes = 0,
TotalFavourites = 0,
WeeksDownloads = 0,
WeeksPlays = 0,
WeeksComments = 0,
WeeksLikes = 1,
WeeksFavourites = 0
});
AddMap<Favourite>(favs => from fav in favs
where fav.DateCreated >= DateTimeOffset.Now.AddDays(-7)
select new
{
Id = fav.AudioId,
ArtistName = (string)null,
Name = (string)null,
TotalDownloads = 0,
TotalPlays = 0,
TotalComments = 0,
TotalLikes = 0,
TotalFavourites = 0,
WeeksDownloads = 0,
WeeksPlays = 0,
WeeksComments = 0,
WeeksLikes = 0,
WeeksFavourites = 1
});
Reduce = results => from result in results
group result by result.Id
into g
select new
{
Id = g.Key,
ArtistName = g.Select(x => x.ArtistName).Where(x => x != null).FirstOrDefault(),
Name = g.Select(x => x.Name).Where(x => x != null).FirstOrDefault(),
TotalDownloads = g.Sum(x => x.TotalDownloads),
TotalPlays = g.Sum(x => x.TotalPlays),
TotalComments = g.Sum(x => x.TotalComments),
TotalLikes = g.Sum(x => x.TotalLikes),
TotalFavourites = g.Sum(x => x.TotalFavourites),
WeeksComments = g.Sum(x => x.WeeksComments),
WeeksDownloads = g.Sum(x => x.WeeksDownloads),
WeeksPlays = g.Sum(x => x.WeeksPlays),
WeeksLikes = g.Sum(x => x.WeeksLikes),
WeeksFavourites = g.Sum(x => x.WeeksFavourites)
};
}
You model is good, stick with it. You won't notice any performance issues at query time, because queries will be run against the precomputed index. So all the work is done asynchronously in a background thread on the server - that makes your queries fast.
Also, you don't need to worry about performance in the index execution, because the Map functions will only be run on new or changed documents and the Reduce function is executed in groups, thus only computing new map results.
Assuming that it is a website we're talking about, your alternative suggestion to denormalize the count into the audio documents would put you intro trouble, because then you would need to load and update the audio document each time somebody clicks on download or play. Of course you wouldn't notice that on a small site, but if you have some simultaneous visitors this will become a problem. In addition, it is much easier to scale out using the Map/Reduce approach and the AudioCounter documents, because then you need to worry less about concurrency and replication - instead, when someone downloads or plays a title, just put in a new AudioCounter document and go on.
One thing that you should be aware of though, are the week-counters. If my assumptions about what they are intended for are true, then they won't work the way you have them now. The problem is, that you cannot have a "range aggregation" (don't know the correct word) inside a map/reduce index - it's always about totals. To do that, you can come up with a facet query that counts the number of records or instead use the index replication bundle to populate a SQL table on which you can do ad-hoc queries. I'm sorry, I don't find a good example for the facet approach right now, maybe I'll put together one on the weekend...
Related
I'm trying to remove a tag from a list of tags using a PATCH request. But while saving changes to the db context I get the following error:.
This the the PATCH code.
[HttpPatch("{id:int}/{field}", Name = "UpdateNote")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult UpdateNote(int id, string field, JsonPatchDocument<CreateNoteDTO> patchNoteDTO)
{
if (id == 0 || patchNoteDTO == null)
return BadRequest();
var note = _db.Notes.AsNoTracking().FirstOrDefault(u => u.ID == id);
if (note == null)
return NotFound();
CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
if (field.Equals("tags"))
{
var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
List<TagDTO> tagDTOs = new List<TagDTO>();
if (tags.Count > 0)
{
foreach (var tag in tags)
{
TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
tagDTOs.Add(tagDTO);
}
}
createNoteDTO.Tags = tagDTOs;
}
patchNoteDTO.ApplyTo(createNoteDTO, ModelState);
if (!ModelState.IsValid)
return BadRequest(ModelState);
Note updateNote = _mapper.Map<Note>(createNoteDTO);
updateNote.ID = id;
updateNote.ChangedDate = DateTime.Now;
_db.Update(updateNote);
if (!field.ToLower().Equals("category"))
_db.Entry(updateNote).Property(u => u.FKCategory).IsModified = false;
_db.Entry(updateNote).Property(u => u.CreatedDate).IsModified = false;
_db.SaveChanges();
return NoContent();
}
My ApplicationDBContext looks like this:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Note> Notes { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//Write Fluent API configurations here
modelBuilder.Entity<Note>()
.HasOne(e => e.Category)
.WithMany(e => e.Notes)
.HasForeignKey(e => e.FKCategory)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Note>()
.HasMany(n => n.Tags)
.WithMany(t => t.Notes)
.UsingEntity(j => j
.ToTable("NoteTag")
.HasData
(
new { NotesID = 1, TagsTagID = 1 },
new { NotesID = 2, TagsTagID = 2 }
));
modelBuilder.Entity<Category>().HasData
(
new Category
{
CategoryID = 1,
CategoryName = "testCategory1",
CreatedDate = DateTime.Now
},
new Category
{
CategoryID = 2,
CategoryName = "testCategory2",
CreatedDate = DateTime.Now
}
);
modelBuilder.Entity<Tag>().HasData
(
new Tag
{
TagID = 1,
TagName = "testTag1",
CreatedDate = DateTime.Now
},
new Tag
{
TagID = 2,
TagName = "testTag2",
CreatedDate = DateTime.Now
}
);
modelBuilder.Entity<Note>().HasData
(
new Note
{
ID = 1,
Title = "testTitle1",
Description = "testDescription1",
FKCategory = 1,
Deleted = false,
CreatedDate = DateTime.Now,
ChangedDate = DateTime.Now,
},
new Note
{
ID = 2,
Title = "testTitle2",
Description = "testDescription2",
FKCategory = 2,
Deleted = false,
CreatedDate = DateTime.Now,
ChangedDate = DateTime.Now,
}
);
}
}
Any suggestions?
Thanks in advance.
Initially I tried without the following if condition:
CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
if (field.Equals("tags"))
{
var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
List<TagDTO> tagDTOs = new List<TagDTO>();
if (tags.Count > 0)
{
foreach (var tag in tags)
{
TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
tagDTOs.Add(tagDTO);
}
}
createNoteDTO.Tags = tagDTOs;
}
But I got a different error:
I wanted to remove a tag form the following object using a PATCH request:
Note Object
how can i add memorycache in this method ?
this is a section of my code that i want to set memory cache on it.
public IActionResult Index(int pageId = 1, string filter = "",
int startPrice = 0, int endPrice = 0, string getType = "", string orderByType = "date",
List<int> selectedGroups = null, List<int> selectedBrand = null, List<int> selectedTags = null
, List<int> selectedsize = null , string Discount = "")
{
ViewBag.selectedGroups = selectedGroups;
ViewBag.selectedTags = selectedTags;
ViewBag.selectedsize = selectedsize;
ViewBag.Discount = Discount;
ViewBag.getType = getType;
ViewBag.Groups = _productService.GetAllGroup();
ViewBag.Tags = _productService.GetTags().Where(c => c.ActiveRow).ToList();
ViewBag.size = _productService.GetSizes().ToList();
ViewBag.pageId = pageId;
return View(_productService.GetProducttype(pageId, filter, startPrice, endPrice, getType, orderByType, selectedGroups, selectedBrand, 24, selectedTags, selectedsize, Discount));
}
private readonly IMemoryCache _memoryCache;
public Constructor (IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public IActionResult Index(int pageId = 1, string filter = "",
int startPrice = 0, int endPrice = 0, string getType = "", string orderByType = "date",
List<int> selectedGroups = null, List<int> selectedBrand = null, List<int> selectedTags = null
, List<int> selectedsize = null , string Discount = "")
{
ViewBag.selectedGroups = selectedGroups;
ViewBag.selectedTags = selectedTags;
ViewBag.selectedsize = selectedsize;
ViewBag.Discount = Discount;
ViewBag.getType = getType;
var groups = new List<Group>();
if (_memoryCache.TryGetValue("groups", out groups)
{
ViewBag.Groups = groups;
}
else
{
groups = _productService.GetAllGroup();
_memoryCache.Set("groups", groups);
ViewBag.Groups = groups;
}
var tags = new List<Tag>();
if (_memoryCache.TryGetValue("tags", out tags)
{
ViewBag.Tags = tags;
}
else
{
tags = _productService.GetTags().Where(c => c.ActiveRow).ToList();
_memoryCache.Set("tags", tags);
ViewBag.Tags = tags;
}
var sizes = new List<Size>();
if (_memoryCache.TryGetValue("sizes", out sizes)
{
ViewBag.size = sizes;
}
else
{
sizes = _productService.GetSizes().ToList();
_memoryCache.Set("sizes", sizes);
ViewBag.size = sizes;
}
var pageId = null;
if (_memoryCache.TryGetValue("pageId", out pageId))
{
ViewBag.pageId = pageId;
}
else
{
_memoryCache.Set("pageId", pageId);
ViewBag.pageId = pageId;
}
return View(_productService.GetProducttype(pageId, filter, startPrice, endPrice, getType, orderByType, selectedGroups, selectedBrand, 24, selectedTags, selectedsize, Discount));
}
I know how to build a simple lambda like x => x > 5:
int[] nbs = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> result1 = nbs.Where(x => x > 5);
ParameterExpression parameter = Expression.Parameter(typeof(int), "x");
ConstantExpression constant = Expression.Constant(5);
BinaryExpression expressionBody = Expression.GreaterThan(parameter, constant);
Expression<Func<int, bool>> expression = Expression.Lambda<Func<int, bool>>(expressionBody, parameter);
IEnumerable<int> result2 = nbs.Where(expression.Compile());
But, how do I create a more complex lambda like this p=>p.FindAttribute("Gender")?.Value == "Female" in the same style as above?
public class Person
{
public bool POI { get; set; } = false;
public string Name { get; set; }
public List<Car> Cars { get; set; }
public List<Attribute> Attributes { get; set; }
public bool PersonOfInterest()
{
return POI;
}
public Attribute FindAttribute(string name)
{
return Attributes.FirstOrDefault(a => a.Name == name);
}
}
public class Attribute
{
public string Name { get; set; }
public string Value { get; set; }
public Attribute(string name, string value) { Name = name; Value = value; }
}
public class Car
{
public string Make { get; set; }
public int Horsepowers { get; set; }
public string Fuel { get; set; }
}
Person p1 = new Person();
p1.Name = "Thom";
p1.POI = true;
p1.Attributes = new List<Attribute>() {new Attribute("Length", "Tall"), new Attribute("Hair", "Long hair")};
p1.Cars = new List<Car>()
{
new Car(){Horsepowers = 100, Make = "Toyota", Fuel = "Diesel"},
new Car(){Horsepowers = 200, Make = "Fiat", Fuel = "Diesel"},
new Car(){Horsepowers = 300, Make = "Audi", Fuel = "Diesel"},
new Car(){Horsepowers = 150, Make = "Ferrari", Fuel = "Petrol"}
};
Person p2 = new Person();
p2.POI = false;
p2.Attributes = new List<Attribute>() { new Attribute("Nationality", "English"), new Attribute("Gender", "Female") };
p2.Name = "Sophie";
p2.Cars = new List<Car>()
{
new Car(){Horsepowers = 500, Make = "McLaren", Fuel = "Diesel"},
new Car(){Horsepowers = 200, Make = "Volvo", Fuel = "Diesel"},
new Car(){Horsepowers = 300, Make = "Audi", Fuel = "Diesel"},
new Car(){Horsepowers = 400, Make = "Ferrari", Fuel = "Diesel"}
};
IEnumerable<Person> res = persons.Where(p=>p.FindAttribute("Gender")?.Value == "Female");
Of course I could always create a new method on Person like:
public bool HasAttributeWithValue(string name, string value)
{
return FindAttribute(name)?.Value == value;
}
But it's still of interest to me if it's possible to construct the complex lambda dynamically!
This piece of code does the job.
ParameterExpression parameter = Expression.Parameter(typeof(Person), "p");
ConstantExpression my_null_object = Expression.Constant(null);
ConstantExpression gender = Expression.Constant("Gender");
MethodCallExpression methodcall = Expression.Call(parameter, typeof(Person).GetMethod("FindAttribute"), gender);
BinaryExpression is_null = Expression.Equal(methodcall, my_null_object);
ConstantExpression constant = Expression.Constant("Female");
MemberExpression member = Expression.Property(methodcall, typeof(Attribute).GetProperty("Value"));
BinaryExpression expressionBody = Expression.Equal(member, constant);
BinaryExpression cond = Expression.AndAlso(Expression.IsFalse(is_null), expressionBody);
Maybe clearer this way
ParameterExpression parameter = Expression.Parameter(typeof(Person), "p");
ConstantExpression my_null_object = Expression.Constant(null);
MethodCallExpression methodcall = Expression.Call(parameter, typeof(Person).GetMethod("FindAttribute"), Expression.Constant("Gender"));
BinaryExpression cond = Expression.AndAlso(
Expression.IsFalse(Expression.Equal(methodcall, my_null_object)),
Expression.Equal(
Expression.Property(methodcall, typeof(Attribute).GetProperty("Value")),
Expression.Constant("Female")
)
);
Null-conditional operator is a language feature. It can be converted to this code:
var attribute = p.FindAttribute("Gender");
return attribute == null ? false : attribute.Value == "Female";
To build an expression tree you can use Expression.Block:
var p = Expression.Parameter(typeof(Person), "p");
var findAttribute = Expression.Call(p,
typeof(Person).GetMethod(nameof(Person.FindAttribute)),
Expression.Constant("Gender"));
var attribute = Expression.Parameter(typeof(Attribute), "attribute");
var body = Expression.Block(
new[] {attribute}, // local variables
new Expression[]
{
Expression.Assign(attribute, findAttribute),
Expression.Condition(
Expression.Equal(attribute, Expression.Constant(null)),
Expression.Constant(false),
Expression.Equal(
Expression.PropertyOrField(attribute, "Value"),
Expression.Constant("Female")))
}
);
var lambda = Expression.Lambda<Func<Person, bool>>(body, p);
I have a model like this:
class PrivatKasse
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
public decimal Betrag { get; set; }
public int BenutzerID { get; set; }
}
and a function that checks if the table is empty. if yes functions adds new rows. The function:
public static void DatabaseChecker()
{
using (var _db = new DataContext())
{
if (!_db.KasseGemeinsam.Any())
{
_db.KasseGemeinsam.Add(new Models.Data.KasseGemeinsamModel() { Jahr = DateTime.Now.Year.ToString(), Monat = MonatenVertauchen.ZahlZuMonaten(Convert.ToInt32(DateTime.Now.Month)), Haushalt = 0, Hygine = 0, Mobel = 0, Nahrung = 0, Schreibware = 0, Sonstiges = 0 });
_db.SaveChanges();
}
if (!_db.KassePrivat.Any())
{
_db.KassePrivat.Add(new Models.Data.KassePrivatModel() { Jahr = DateTime.Now.Year.ToString(), Monat = MonatenVertauchen.ZahlZuMonaten(Convert.ToInt32(DateTime.Now.Month)), UserID = UserIdentity.UserID, Fahrkosten = 0, Hygine = 0, Mobel = 0, Nahrung = 0, Schreibware = 0, Sonstiges = 0 });
_db.SaveChanges();
}
if (!_db.GemeinsamKasse.Any())
{
_db.GemeinsamKasse.Add(new Models.Data.GemeinsamKasse() { Betrag = 0 });
_db.SaveChanges();
}
if (!_db.PrivatKasse.Any())
{
List<int> userIDs = new List<int>();
foreach (var item in _db.UsersTbl)
{
userIDs.Add(item.ID);
}
using (var _db2 = new DataContext())
{
foreach (var item in userIDs)
{
_db2.PrivatKasse.Add(new Models.Data.PrivatKasse() { BenutzerID = item, Betrag = 0 });
}
_db2.SaveChanges();
}
}
}
But I get an SqlExeption :
System.Data.Entity.Infrastructure.DbUpdateException: "An error occurred while updating the entries. See the inner exception for details."
UpdateException: An error occurred while updating the entries. See the
inner exception for details.
SqlException: Violation of PRIMARY KEY constraint
'PK_dbo.PrivatKasses'. Cannot insert duplicate key in object
'dbo.PrivatKasses'. The duplicate key value is (0).
The statement has been terminated.
How can i fix this problem?
I believe the issue is because you are not providing the id (and the default in a int is 0) since you declare
[DatabaseGenerated(DatabaseGeneratedOption.None)]
which means that the db will not create the id, I recommend to use Identity instead
[DatabaseGenerated(DatabaseGeneratedOption.Identity )]
then you should be able to use
_db2.PrivatKasse.Add(new Models.Data.PrivatKasse() { BenutzerID = item, Betrag = 0 })
otherwise provide the id
_db2.PrivatKasse.Add(new Models.Data.PrivatKasse() {ID= customID, BenutzerID = item, Betrag = 0 })
select case statement in linq query.
Here is the query on sql:
select case when DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101)) = 0 then
Sum([Order].OrderSubtotal)
else
case when (DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101))/30) = 0 then Sum([Order].OrderSubtotal) else
Sum([Order].OrderSubtotal)/
(DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101))/30)
end
end as 'Account Value' from [order] where And Account.ID = #Act_ID
I am trying the code here:
var query = _orderRepository.Table;
query = query.Where(o => o.AccountId == accountId);
In query i am getting my value.
After query statement what should i write??
how do i write for case statement using linq???
#Manoj, may be the below code helps you. This sample C# project may solve the problem you have.
using System;
using System.Collections.Generic;
using System.Linq;
namespace DateDiffIssue
{
class Program
{
static void Main(string[] args)
{
// Preparing data
var data = new Order[] {
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 10:00"), OrderSubtotal = 100 },
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 12:00"), OrderSubtotal = 150 },
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 14:00"), OrderSubtotal = 150 }
};
// Selection
var selected = (from item in data
let accountData = data.Where(w => w.AccountID == 1)
let minDate = accountData.Min(m => m.CreatedOnUtc).Date
let maxDate = accountData.Where(w => w.AccountID == 1).Max(m => m.CreatedOnUtc).Date
let isSameDate = minDate == maxDate
let basedOn30Days = (maxDate - minDate).TotalDays / 30
let isInside30Days = (int)basedOn30Days == 0
let accountDataSum = accountData.Sum(s => s.OrderSubtotal)
select new
{
AccountValue = isSameDate ? accountDataSum :
isInside30Days ? accountDataSum :
accountDataSum / basedOn30Days
}).Distinct();
// Print each order
selected.ToList().ForEach(Console.WriteLine);
// Wait for key
Console.WriteLine("Please press key");
Console.ReadKey();
}
}
internal class Order
{
public int AccountID { get; set; }
public DateTime CreatedOnUtc { get; set; }
public int OrderSubtotal { get; set; }
}
}