Hello, I need advice on the best way to implement many-to-many relationships involving the User entity. Here’s my scenario:
Entities Involved: *Work Sites and Services: I have several dynamic work sites and services. *User Types: There are two types of users: * Internal users: They can add and modify services and sites. * Commercial (customer) users: They are associated with specific services and sites and should only be able to view tasks and activities assigned to those sites. Relationships:
Questions:
Thanks
I share code about Services and many to many rel ServiceIdentityUser and his joint table
namespace CoopService.Services
{
public abstract class ServiceBase : FullAuditedAggregateRoot<int>
{
[NotNull]
public virtual string Code { get; set; }
[NotNull]
public virtual string Description { get; set; }
public ICollection<ServiceIdentityUser> IdentityUsers { get; private set; }
protected ServiceBase()
{
}
public ServiceBase(string code, string description)
{
Check.NotNull(code, nameof(code));
Check.Length(code, nameof(code), ServiceConsts.CodeMaxLength, 0);
Check.NotNull(description, nameof(description));
Code = code;
Description = description;
IdentityUsers = new Collection<ServiceIdentityUser>();
}
public virtual void AddIdentityUser(Guid identityUserId)
{
Check.NotNull(identityUserId, nameof(identityUserId));
if (IsInIdentityUsers(identityUserId))
{
return;
}
IdentityUsers.Add(new ServiceIdentityUser(Id, identityUserId));
}
public virtual void RemoveIdentityUser(Guid identityUserId)
{
Check.NotNull(identityUserId, nameof(identityUserId));
if (!IsInIdentityUsers(identityUserId))
{
return;
}
IdentityUsers.RemoveAll(x => x.IdentityUserId == identityUserId);
}
public virtual void RemoveAllIdentityUsersExceptGivenIds(List<Guid> identityUserIds)
{
Check.NotNullOrEmpty(identityUserIds, nameof(identityUserIds));
IdentityUsers.RemoveAll(x => !identityUserIds.Contains(x.IdentityUserId));
}
public virtual void RemoveAllIdentityUsers()
{
IdentityUsers.RemoveAll(x => x.ServiceId == Id);
}
private bool IsInIdentityUsers(Guid identityUserId)
{
return IdentityUsers.Any(x => x.IdentityUserId == identityUserId);
}
}
}
namespace CoopService.Services
{
public class ServiceIdentityUser : Entity
{
public int ServiceId { get; protected set; }
public Guid IdentityUserId { get; protected set; }
private ServiceIdentityUser()
{
}
public ServiceIdentityUser(int serviceId, Guid identityUserId)
{
ServiceId = serviceId;
IdentityUserId = identityUserId;
}
public override object[] GetKeys()
{
return new object[]
{
ServiceId,
IdentityUserId
};
}
}
}