0

I have the following database models and its properties:

  • User (id, role_id, name, email, password)
  • Role (id, name, description, active)
  • User2Role (user_id, role_id)
  • Customer (id, name, user_id)

A User has many roles. A Customer is a User. But a User is not allways a Customer (e. g. Admin)

Now, how can i represent it in my domain layer?

Example 1:

public class User {

    private long userID;
    private List<Long> roleIds;

    private String userName;
    private String userEmail;
    private String userPassword;
}

Example 2:

public class User {

    private long userID;
    private List<Role> roles;

    private String userName;
    private String userEmail;
    private String userPassword;
}

Same goes for customer, should i only save the user-id in customer or create a user object and save the user object in customer?

  • Is not Customer a role? In the given model, a Customer can be Admin. Does it make sense? – Laiv May 1 '17 at 21:07
  • I think the role_id field in the User database model is an error and should be removed. – Erik Eidt May 1 '17 at 22:57
  • Sorry for the late response. Thanks for the hints and advice. @Laiv Customer does have a role, but i cover it already with the relation to User, since Customer is a User. – Rep May 6 '17 at 22:37
2

Because C# (and Java) uses references, the code

private List<Role> roles;

is perfectly valid.

roles is a list of Role references; you're not storing copies of the original Role objects, or even the original Role objects themselves. Rather, the Role objects are stored in some arbitrary locations in memory, and the roles collection merely stores "pointers" to those objects.

It doesn't cost you anything extra (like additional memory), in other words.

This arrangement allows you to reference the same role object in each of several User objects. Unlike your roleID example, it still gives you access to all of the fields in the referenced role.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.