在C#中使用dapper将外键插入数据库

时间:2019-03-12 02:56:14

标签: c# sql-server dapper

我想使用dapper在C#中使用外键插入sql表,这是我的代码。当我这样做时,会给我带来转换错误。

public class LoanModel
{
    public int ID { get; set; }
    public CustomerModel CustomerID { get; set; }
    public int Amount { get; set; }
    public InterestModel Interest { get; set; }
    public DateTime Date { get; set; }
}

这是填充数据网格视图的方法:

List<LoanModel> Loans = new List<LoanModel>();

public void FillCustomersDataGridview()
{
    try
    {
        DataAccess.ShowLoan(SearchCustomTextBox.Text.Trim());
        dataGridView1.DataSource = Loans;
    }
    catch (Exception ERE)
    {
        MessageBox.Show($"An error occured: {ERE.Message}");
    }
}

这是将数据插入数据库的方法:

public static void GetLoan(int id, int customerID, int amount, int interest, DateTime loanDateDateTimePicker)
{
    using (IDbConnection Con = new SqlConnection(Helper.ConnectionString("DatabaseConnection")))
    {
        LoanModel Loan = new LoanModel { ID = id, CustomerID = customerID, Amount = amount, Interest = interest, Date = loanDateDateTimePicker };
        List<LoanModel> newLoan = new List<LoanModel>();
        newLoan.Add(Loan);
        Con.Execute("spGetLoan @ID, @CustomerID, @Amount, @Interest, @Date", newLoan);
    }
}

1 个答案:

答案 0 :(得分:0)

为什么有通过列表将数据插入数据库时​​间。

您的查询

List<LoanModel> newLoan = new List<LoanModel>();
                    newLoan.Add(Loan);
                    Con.Execute("spGetLoan @ID, @CustomerID, @Amount, @Interest, @Date", newLoan);

请直接通过仅模型

Con.Execute("spGetLoan @ID, @CustomerID, @Amount, @Interest, @Date", Loan);