拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 当我从数据库中查询资料时,它不会传递给C#和SQLite中的基类

当我从数据库中查询资料时,它不会传递给C#和SQLite中的基类

白鹭 - 2022-02-24 1968 0 0

我有一个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

但是,我确实认为您会从使用公共属性/栏位中受益,因为它会在映射资料时为您提供更多选项/控制。

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *