Error: Dapper Produces ‘Invalid object name’ on Insert operation
Issue Description
Today in this article, we will cover below aspects,
Dapper operation in the runtime produces the below error,
System.Data.SqlClient.SqlException (0x80131904): Invalid object name ‘EmployeeDbs’ at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection,….
Resolution
As per Dapper documentation, “POCO names should match the table name in the database. Pluralized table names are supported through the PlurizedAutoClassMapper.”
Below was the POCO name I was using which was giving me an error,
public partial class EmployeeDB
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string ZipCode { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string ID { get; set; }
}
I was running the below Insert command,
using (IDbConnection db = new SqlConnection(_connectionString))
{
db.Insert(new EmployeeDB() { FirstName = "Youabcd", LastName
= "test", Address ="sdasda", Country ="USA", ID ="13213",
State ="NY", ZipCode ="11111"});
}
So to fix the issue I had to use Table Attribute on my POCO entities as below otherwise dapper extension consider the pluralized table name i.e EmployeeDBs.
[Table("EmployeeDB")]
public partial class EmployeeDB
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string ZipCode { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string ID { get; set; }
}
So finally below POCO resolve the issue with Table attribute,
and the operation was successful!!
For a complete example, please visit the below article,
Did I miss anything else in these resolution steps?
Did the above steps resolve your issue? Please sound off your comments below!
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.
Thanks , Able to resolve the issue !
Thank you, Esam for the confirmation. I appreciate your time.