I Want to insert into sql table with foreign key in c# using dapper, Here is my code. 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);