I have a class Customer which inherits from class Person, but when I am querying data from the database, it doesn't pass to the base class Person. Data is just passed to Customer class.
The CustomerInfo database table data has columns:
Id - FirstName - LastName - NickName - Address - RegistrationDate
I use Dapper to connect to my SQLite database.
Why does this happen, and I want to pass data to the constructor but I don't know how.
public class PersonModel
{
int Id;
string FirstName;
string LastName;
public PersonModel() { }
public PersonModel(string firstName, string lastName, int id = 0)
{
Id = id;
FirstName = firstName;
LastName = lastName;
}
public string GetFullName()
{
return $"{FirstName} {LastName}";
}
}
public class CustomerModel : PersonModel
{
string NickName;
string Address;
string RegistrationDate;
public CustomerModel() { }
public CustomerModel(string firstName, string lastName,
string address, string registrationDate = "",
string nickName = "", int id = 0) : base(firstName, lastName, id)
{
NickName = nickName;
Address = address;
RegistrationDate = registrationDate;
}
public string FullInfo
{
get
{
return $"{GetFullName()} {RegistrationDate}";
}
}
}
public class CustomerDataAccess
{
public static List<CustomerModel> LoadCustomers()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionStrings()))
{
IEnumerable<CustomerModel> output = cnn.Query<CustomerModel>("SELECT * FROM CustomerInfo", new DynamicParameters());
return output.ToList();
}
}
private static string LoadConnectionStrings(string id = "Default")
{
return ConfigurationManager.ConnectionStrings[id].ConnectionString;
}
}
CodePudding user response:
your query returns only customerinfo table column, it should have a join with a person table, if you want to return info from both tables.
IMHO I don't see what are you going to win using constructor instead of getters setters.Try this
public class PersonModel
{
public int Id {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
....and so on
}
the same with another class
CodePudding user response:
One of the problems is that you have a default constructor and a parameterized constructor. Dapper is using the default constructor which is why the fields in PersonModel are null/default. You can change the access modifier to private for the customer model - private CustomerModel() { } - and it should pick the parameterized constructor instead.
However, when you're using a parameterized constructor you need to match the order of the columns returned from the query with the order of the parameters in the constructor you want to use. There is no guarantee of the order the columns will be returned when using select * from....
So, you should update the SQL query to:
SELECT FirstName, LastName, Address, RegistrationDate, Nickname, Id FROM CustomerInfo
However, I do think you'd benefit from using public properties/fields as it would give you more options/control when mapping the data.
