Convert Entity data model to Data Transfer Object

c# entity-framework-core linq

Question

I have these two classes

enum CustomerType {
 CitizenBank = 0,
  Wellsfargo = 1
}




public abstarct class CustomerDto {
 int customerId {
  get;
  set;
 }
 string customerName {
  get;
  set;
 }
 string CustometAddress {
  get;
  set;
 }
 int CustomerTypeId {
  get;
  set;
 }
}
public CitizenBank: CustomerDto {}


public Wellsfargo: CustomerDto {}


Public Class CustomerEntity {

int customerId {
  get;
  set;
 }
 string customerName {
  get;
  set;
 }
 string CustometAddress {
  get;
  set;
 }
 int CustomerTypeId {
  get;
  set;
 }
}

I wrote a class to convert from entity to DTO

public class EntityModelToModel {
 ///Method to convert 
 public CustomerDto ToDto(CustomerEntity customerEntity) {
  /// returns type customerDto based on customertypeid
  switch (CustomerType) {
   case Wellsfargo
   return New Wellsfargo()  
   case citizen
   return new citizen()  //calls method that converts from customer Entity to citizen
  }

 }

I have method to check if my types match

 public bool CanExecute(CustomerEntity customerEntity) {
   foreach(var customerType in Enum.GetValues(typeof(Enums.customerType) if (customerEntity.CustomerType == customerType)
      return true
     else
      false
    }
   }

Now my calling code I have array of CustomerEntity[] which have two items of customerid for wellsfargo and citizens. I want to do this

   var res = CustomerEntity[].where(x => EntityModelToModel.CanExecute(x).Select(x => EntityModelToModel.ToDto(x)) 

My problem is:

If my array has two items this only checks the first items and returns.

What I want is it should check for two items and return them.

1
0
3/19/2020 8:45:16 PM

Accepted Answer

I think that you should change your CanExecute method like this:


public static class EntityModelToModel
{

    // ...

    public static bool CanExecute(CustomerEntity customerEntity)
    {
        foreach (var customerType in Enum.GetValues(typeof(CustomerType)))
        {
            if (customerEntity.CustomerTypeId == (int)customerType)
            {
                return true;
            }
        }

        return false;
    }
}

Because your method break execution flow after first check.

1
3/23/2020 6:15:45 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow