1

How can I check that entity itself exists before executing Update or Delete?

I tried using something like the code below, but getting an error "Property name must be specified". How to implement such logic?

public CustomValidator()
{
     RuleFor(x=>x).Must(ExistsInDatabase).WithMessage("Attempt to work with nonexistent entity");
}

private bool ExistsInDatabase(MyClass myClassInstance)
{

     if (myClassInstance == null)
           return false;

     return true;

   }

UPDATE: the question concerns the syntax in RuleFor() - is it possible to use (x=>x) without specifying particular property? or somehow else to check state of the whole entity being validated?

1 Answer 1

2

I believe that you will need to write more functionality into your ExistsInDatabase class, so that it is able to perform a lookup in the database to see whether a entity exists that has the same primary key perhaps.

If you are using Entity Framework, you could use generics on the ExistsInDatabase class, so that it can call your context. You can add a simple helper to your context class, something along these lines

public virtual IDbSet<T> DbSet<T>() where T : class
    {
        return this.Set<T>();
    }

Once you have a set, you can use the EF Find method, that would search based on primary key. Something like this for example

var result = context.DbSet<Business>().Find(1);
return result == null ? false : true;
Sign up to request clarification or add additional context in comments.

2 Comments

how to pass the whole entity to the method ExistsInDatabase()?
when you say RuleFor(x => x).Must(ExistsIndatabase) what is the value of x at that point? Could you show how you use this, perhaps ad in test method that shows it being used. From there we would be able to determine how you could proceed. On thing that I do, is all my entities inherit from a base class, that is a abstract class with certain properties. If you had that, you could simply expect that as a parameter in your ExistsInDatabase method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.