简体   繁体   English

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

[英]Insert foreign key into database using dapper in c#

I Want to insert into sql table with foreign key in c# using dapper, Here is my code. 我想使用dapper在C#中使用外键插入sql表,这是我的代码。 When I do it this way it gives me a conversion error. 当我这样做时,它给了我一个转换错误。

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

This is the method that fills the data gridview: 这是填充数据网格视图的方法:

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

This is the method that inserts the data into the database: 这是将数据插入数据库的方法:

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

Why you have pass list to insert data into the database time. 为什么要有通过列表以将数据插入数据库时​​间。

Your Query 您的查询

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

Please direct pass only model 请直接通过仅模型

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM