Where to place calculated property of HasChildren for Domain Model? - domain-driven-design

We have an Department model (domain-driven design). Each department has its child departments, so domain model looks like
public class Department
{
int Id { get; set; }
...
ICollection<Department> Children { get; set; }
}
At the API domain models of the same hierarchy path, coming from repository, it will transforms to DTO trough AutoMapper and does not include children by default.
public class DepartmentDto
{
int Id { get; set; }
...
ICollection<DepartmentDto> Children { get; set; } // Empty set.
}
Does it a good way to add [NotMapped] bool HasChildren property to the Department domain model to show or hide expand arrows at the client? For lazy load.
This field smells strange: can be filled or can be not (depends on query).
Repository returns a collection of departments, belongs to parent Id (may become Null to root nodes):
ICollection<Department> GetDepartments(int? parentId = null);

So, based on Lucian Bargaoanu comments, I've found the solution:
IDepartmentRepository.cs
IQueryable<Department> GetDepartmentsQuery(int? parentId = null);
DepartmentsController.cs (API):
[HttpGet]
public async Task<ActionResult<ICollection<DepartmentDto>>> GetRootDepartments()
{
var dtoItems = await _repository.GetDepartmentsQuery()
.ProjectTo<DepartmentDto>(_mapper.ConfigurationProvider)
.ToListAsync();
return Ok(dtoItems);
}
AutoMapper configuration:
CreateMap<Department, DepartmentDto>()
.ForMember(x => x.HasChildren,
opts => opts.MapFrom(x => x.Children.Any()))
.ForMember(x => x.Children,
opts => opts.Ignore());

Related

How to initialize sub-collections along with aggregate root in abp.io

What I want to achieve is to figure out where to initialize my sub-collections with aggregate root itself and validate business rules in a best practice way.
Here is my AppService:
public async Task<ReservationDto> CreateReservationAsync(CreateReservationInputDto input)
{
var reservation = await _reservationSystemManager.CreateAsync(
input.ReserverNotes
);
//should i send them directly to manager's createasync method but RequestedItems are dto objects.
//should i iterate through RequestedItems here and send them to manager one by one.
// where to throw business exception if RequestedItems count is 0.
}
Here is my inputdto:
public class CreateReservationInputDto
{
public string ReserverNotes { get; set; }
public Enum.Status Status { get; set; }
public List<CreateReservationItemInputDto> RequestedItems { get; set; }
}
Here is my aggregate root:
public class Reservation : FullAuditedAggregateRoot<Guid>
{
public Enum.Status Status { get; private set; }
public string ReserverNote { get; private set; }
public ICollection<ReservationItem> ReservationItems { get; set; }
public ICollection<OverduePayment> OverduePayments { get; set; }
private Reservation() { }
internal Reservation(
Guid id,
Enum.Status status,
[NotNull] string reserverNote,
) : base(id)
{
ReserverNote = reserverNote;
Status = status;
ReservationItems = new Collection<ReservationItem>();
OverduePayments = new Collection<OverduePayment>();
}
//I could not decide where and how to call this function from Domain Service.
internal void AddReservationItem(ReservationItem reservationItem)
{
if (ReservationItems.Any(r => r.Id == reservationItem.Id))
{
return;
}
ReservationItems.Add(reservationItem);
}
}
Well, depends on your business rules and your use cases. For example, if a reservation must have some reservation items, then I would create it in reservation constructor. Otherwise, if after creating reservation I can add new reservation items then I would be another use case and then AddReservationItem has sense for me.
Generally, if you need to inject more than one service (E.g. IUserRepository and IReservationItemsRepository) for validating your collection or any other property, you can create a domain service and implement your business logic and validate your collection with your needs.
If you don't need to inject any service to implement your business rules you can do it directly in your application service methods. In such cases, you can use data annotations for validating your properties in DTO classes as stated in here.
//should i send them directly to manager's createasync method but RequestedItems are dto objects.
//should i iterate through RequestedItems here and send them to manager one by one.
//where to throw business exception if RequestedItems count is 0.
In these three questions you've asked, should take it separately.
For instance, If you create a domain service class, it could be better to throw an exception if the RequestedItems count is 0 in that class' method. (And you can call, your AddReservationItem method from the domain service's method in that case.)
You can also check the best-practices documents of ABP.

categorize ServiceStack methods

Imagine I have two "areas" in my API, inventory and orders. I can quite easily group all methods related to inventory into "/inventory/" and to orders "/orders/" routes.
However, when I go to the root page of API where all methods are shown (IndexOperations.html) all methods are mixed together into one big list.
Is there any way to group methods from different areas on that list? For example show something like this on the operations index page.
Inventory
Method1
Method2
Orders
Method1
Method2
Group your operations:
If you group your DTOs into a static class as shown below, then ordering will be taken care of automatically assuming you want the groups alphabetically.
public static class UserOperations
{
[Route("/Users","POST")]
public class CreateUserRequest
{
public string Name { get; set; }
public int Age { get; set; }
}
...
}
public static class DuckOperations
{
[Route("/Ducks","POST")]
public class CreateDuckRequest
{
public string Name { get; set; }
public int Age { get; set; }
}
...
}
Alternatively specify the sort:
The ServiceStack MetadataFeature in v4.09+ provides access to the IndexPageFilter which lets you specify specify the Sort function that is applied to the index pages' OperationNames, where the OperationName is the full type name of the DTO.
var metadata = Plugins.First(x => x is MetadataFeature) as MetadataFeature;
// This is the default sort, replace with one that groups
metadata.IndexPageFilter = (page) => page.OperationNames.Sort((a,b) => b.CompareTo(a));
I hope this helps.

Including a base member doesn't seem to work in Entity Framework 5

here are my entities:
public abstract class ResourceBase
{
[Key]
int Id { get; set; }
[ForeignKey("Resource")]
public Guid ResourceId { get; set; }
public virtual Resource Resource { get; set; }
}
public class Resource
{
[Key]
public Guid Id { get; set; }
public string Type { get; set; }
}
public class Message : ResourceBase
{
[MaxLength(300)]
public string Text { get; set; }
}
And then my query is something like this:
var msgs = messages.Where(x=>x.Id == someRangeOfIds).Include(m=>m.Resource).Select(x => new
{
message = x,
replyCount = msgs.Count(msg => msg.Id = magicNumber)
});
I am running this with proxy creation disabled, and the result is all the messages BUT with all the Resource properties as NULL. I checked the database and the Resources with matching Guids are there.
I drastically simplified my real life scenario for illustration purposes, but I think you'll find you can reproduce the issue with just this.
Entity Framework 5 handles inherited properties well (by flattening the inheritence tree and including all the properties as columns for the entity table).
The reason this query didn't work was due to the projection after the include. Unfortunately, the include statement only really works when you are returning entities. Although, I did see mention of a solution which is tricky and involves invoking the "include" after the shape of the return data is specified... If anyone has more information on this please reply.
The solution I came up with was to just rephrase the query so I get all messages in one query, and then in another trip to the database another query that gets all the reply counts.
2 round trips when it really should only be 1.

How update an entity inside Aggregate

I have an aggregate named Campaigns every with a root entity named campaign, this root entity has a list of attempts (entity)
public class Attempts: IEntity<Attempts>
{
private int id;
public AttempNumber AttemptNumber {get;}
//other fields
}
public class Campaign: IEntity<Campaign> //root
{
private int id;
public IList<Attempt> {get;}
//other fields
}
Im using a method to add a campaign attempt
public virtual void AssignAttempts(Attempts att)
{
Validate.NotNull(att, "attemps are required for assignment");
this.attempts.add(att);
}
Problem comes when i try to edit a specific item in attempts list. I get Attempt by AttempNumber and pass it to editAttempt method but i dont know how to set the attempt without deleting whole list and recreate it again
public virtual void EditAttempts(Attempts att)
{
Validate.NotNull(att, "attemps are required for assignment");
}
Any help will be appreciated!
Thanks,
Pedro de la Cruz
First, I think there may be a slight problem with your domain model. It seems to me like 'Campaign' should be an aggregate root entity having a collection of 'Attempt' value objects (or entities). There is no 'Campaigns' aggregate unless you have a parent concept to a campaign which would contain a collection of campaigns. Also, there is no 'Attempts' entity. Instead a collection of 'Attempt' entities or values on the 'Campaign' entity. 'Attempt' may be an entity if it has identity outside of a 'Campaign', otherwise it is a value object. The code could be something like this:
class Campaign {
public string Id { get; set; }
public ICollection<Attempt> Attempts { get; private set; }
public Attempt GetAttempt(string id) {
return this.Attempts.FirstOrDefault(x => x.Number == id);
}
}
class Attempt {
public string Number { get; set; }
public string Attribute1 { get; set; }
}
If you retrieve an Attempt from the Campaign entity and then change some of the properties, you should not have to insert it back into the campaign entity, it is already there. This is how the code would look if you were using NHibernate (similar for other ORMs):
var campaign = this.Session.Get<Campaign>("some-id");
var attempt = campaign.GetAttempt("some-attempt-id");
attempt.Attribute1 = "some new value";
this.Session.Flush(); // will commit changes made to Attempt
You don't need an Edit method. Your code can modify the Attempts in-place, like so:
Attempt toModify = MyRepository.GetAttemptById(id);
toModify.Counter++;
toModify.Location = "Paris";
MyRepository.SaveChanges(); // to actually persist to the DB
Of course how you name the SaveChanges() is up to you, this is the way Entity Framework names its general Save method.

Entity Framework 4 - TPH Inheritance in Features CTP5 (code first) with "IS NULL" discriminator

Hey guys,
I'm trying to create a TPH mapping on a hierarchy where the discriminating clause is the classical "IS NOT NULL" / "IS NULL" case.
Here is the example, database wise:
CREATE TABLE info.EducationTypes
(
ID INT NOT NULL PRIMARY KEY,
Name NVARCHAR(64) NOT NULL,
FKParentID INT NULL REFERENCES info.EducationTypes(ID)
)
the idea is to have a class hierarchy like the following one:
public abstract class EducationType
{
public int ID { get; set; }
public string Name { get; set; }
}
public class MainEducationType : EducationType
{
public IEnumerable<SubEducationType> SubTypes { get; set; }
}
public class SubEducationType : EducationType
{
public MainEducationType MainType { get; set; }
}
I got this schema "working" in the classic xml model, but I really can't find a way to get it working by using the code first approach. This is what I tried...
var educationType = modelBuilder.Entity<EducationType>();
educationType.Map<MainEducationType>(m => m.Requires("FKParentID").HasValue(null));
educationType.Map<SubEducationType>(m => m.Requires("FKParentID"));
Do you have any suggestion?
Unfortunately, having a null value for the discriminator column in TPH mapping is not currently supported in CTP5. This is confirmed by EF team on here and also here. They are looking at it to see if they can make it work for the RTM though.

Resources