我有一個Customer繼承自 class 的類Person,但是當我從資料庫中查詢資料時,它不會傳遞給基類Person。資料只是傳遞給Customer類。
資料庫表CustomerInfo資料有列:
Id - FirstName - LastName - NickName - Address - RegistrationDate
我使用 Dapper 連接到我的 SQLite 資料庫。
為什么會發生這種情況,我想將資料傳遞給建構式但我不知道如何。
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;
}
}
uj5u.com熱心網友回復:
您的查詢僅回傳 customerinfo 表列,如果您想從兩個表中回傳資訊,它應該與 person 表連接。
恕我直言,我看不出使用建構式而不是 getter 設定器會贏得什么。試試這個
public class PersonModel
{
public int Id {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
....and so on
}
與另一個班級相同
uj5u.com熱心網友回復:
問題之一是您有一個默認建構式和一個引數化建構式。Dapper 使用默認建構式,這就是為什么其中的欄位PersonModel為空/默認的原因。您可以將客戶模型的訪問修飾符更改為私有 - private CustomerModel() { }- 它應該選擇引數化建構式。
但是,當您使用引數化建構式時,您需要將查詢回傳的列的順序與要使用的建構式中的引數順序相匹配。無法保證使用select * from....
因此,您應該將 SQL 查詢更新為:
SELECT FirstName, LastName, Address, RegistrationDate, Nickname, Id FROM CustomerInfo
但是,我確實認為您會從使用公共屬性/欄位中受益,因為它會在映射資料時為您提供更多選項/控制。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/412245.html
標籤:
上一篇:帶有雙鍵C 的映射
下一篇:Java中的抽象類和方法
