当我从数据库中查询数据时,它不会传递到 C# 和 SQLite 中的基 class

When I am querying data from database it doesn't passes to the base class in C# and SQLite

我有一个 class Customer 继承自 class Person,但是当我从数据库中查询数据时,它没有传递到 base classPerson。数据刚刚传递给 Customer class.

CustomerInfo数据库table数据有列:

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;
    }
}

您的查询 return 只有 customerinfo table 列,如果您想 return 来自两个 tables.

恕我直言,我看不出使用构造函数而不是 getter 有什么好处 setters.Try this

public class PersonModel
{
        public int Id {get; set;}
        public  string FirstName {get; set;}
        public string LastName {get; set;}
        ....and so on
}

另一个一样class

其中一个问题是您有一个默认构造函数和一个参数化构造函数。 Dapper 使用默认构造函数,这就是 PersonModel 中字段为 null/default 的原因。您可以将客户模型的访问修饰符更改为私有 - private CustomerModel() { } - 它应该选择参数化构造函数。

但是,当您使用参数化构造函数时,您需要将从查询返回的列的顺序与您要使用的构造函数中的参数顺序相匹配.使用 select * from....

时,无法保证返回列的顺序

因此,您应该将 SQL 查询更新为:

SELECT FirstName, LastName, Address, RegistrationDate, Nickname, Id FROM CustomerInfo

但是,我确实认为您会从使用 public properties/fields 中获益,因为它会在映射数据时给您更多 options/control。

其中一个问题是 c# 中的 int 数据类型与 sqlite 中的 INTEGER 数据类型不匹配,我使用 long 而不是 [=10= 解决了这个问题]