Should i validate if related entity exists before insert?

220 views Asked by At
class Customer
{
    public int Id { get; set; }
}

class Sale
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
}

class SaleService
{

    public void NewSale(Sale sale)
    {
        //Should i validate if Customer exists by sale.CustomerId before call save?

        saleRepository.InsertOrUpdate(sale);
    }
}

I'm using Domain Driven Design and Entity Framework. Should i validate if Customer exists by sale.CustomerId before call save?

1

There are 1 answers

6
Khanh TO On BEST ANSWER

I usually don't do that. Normally, these information comes from the client which was loaded before (it existed). However, there are cases that the CustomerId is missing at the time you update your db.

  • Due to concurrency when many users access the system at the same time. But this case should be solved selectively using optimistic concurrency control (version). We usually don't try to handle concurrency in all the cases as it's almost impossible to do so and doing that also has side effects like performance issues, complexity,... We focus only on some critical code in the system that would cause problems if there is a concurrency issue.

  • A client tries to hack the system by sending an inappropriate CustomerId. But this is another issue that should be checked based on authorization or something like that.

In most of the cases, I think a foreign key constraint in db is enough.