0

Is it possible to check whether a list already has an object without considering its inheritance?

For better context, I'm using EF Core to get the list and CQRS to add/update/remove entities. I need to check if the command is equal to any entity in this list, but I can't check any of the Entity properties.

Code example:

public class Entity
{
    public Entity()
    {
        Id = Guid.NewGuid();
    }

    public Guid Id { get; private set;}
    //more properties in the future
}

public class Something : Entity
{
    //constructor

    public prop1 { get; private set;}
    public prop2 { get; private set;}
    //add 10 more properties
}

public class CreateSomethingCommand
{
    //constructor

    public prop1 { get; set;}
    public prop2 { get; set;}
    //add 10 more properties
}

public async Task Handle(CreateSomethingCommand command)
{                                    
    var somethingList = await _somethingRepository.GetSomethingList();

    foreach (var item in somethingList)
    {
        //if (item.CompareProperties(command) is false)
            //continue;                  

        await _somethingRepository.Create(item);
    }            
}

Now I want to check if a list of this Something already has that command added.

The first thing I did was a huge if to check each property, but it is not ideal.

The second thought was an ExistSomething method in the EF core call, but it would take Entity properties into account.

I'm just out of ideas to make it more readable and clean.

  • 1
    Implement IEquatable Interface and use that interface for comparison?? You can simply compare GUID if that is your primary key – Alander Aug 23 '21 at 15:29
  • You could surely implement some fancy comparer class that gets the properties with the same name and type from two different object types using reflection, but this would be surely slower than your `CompareProperties` method and would only make sense if you have more classes like Something and CreateSomethingCommand - or - you want properties added later to your types be included automatically in the equality comparison. – Steeeve Aug 23 '21 at 16:14
  • @Alander but the Guid will be different, since I'm creating a new Something. The problem is not the PK, it is the whole object, just want to avoid adding it twice. For the time being, I will keep using a huge if to compare each property. – Felipe Alves Aug 23 '21 at 16:56
  • @Steeeve I will try the fancy comparer as this will only happen a few times a year. Hadn't thought of that, thanks. – Felipe Alves Aug 23 '21 at 17:07

0 Answers0