Adiqq
Adiqq

Reputation: 493

Model validation, database constraints

I'm trying to add some architecture to my projects and enrich my models. I started with CQS (implementation similar to that one: CQS-Sample) and here's my first problem.

Let's say I have two classes like these below:

public class Network
{
    public int Id { get; set; }
    public User User { get; set; }
    private IQueryFactory _queryFactory { get; set; }

    public Network(IQueryFactory queryFactory)
    {
        _queryFactory = queryFactory;
    }

    public void AddUser(User user)
    {
        if(this.User == null && user != null)
        {
            userHasUniqueEmail(user);
            this.User = user;
        }

    }

    private void userHasUniqueEmail(User user)
    {
        bool isUnique = _queryFactory.ResolveQuery<INewUserUniqueQuery>().Execute(user.Email);
        if (!isUnique)
        {
            throw new ArgumentException("E-mail is not unique");
        }
    }
}

public class User
{
    public int Id { get; set; }
    public string Email { get; set; }
}

Network object can have User, but I need to check first in database that given e-mail doesn't already exists or do some other checkings, so my commands will be executed successfully. By adding user I mean adding completely new User to database. Would it be correct way to do this?

Upvotes: 0

Views: 58

Answers (1)

teo van kot
teo van kot

Reputation: 12491

You can do it the way you do it now and it's ok.

Another option is to make this Validation in Contoller. Then you should use Remote attribute. And Move your IsEmailUnique(string mail) method to Controller.

If you want to know how you can do it with email check - this question will help you.

Upvotes: 1

Related Questions