C# – How to update a DB table using a POCO class bound in a DataGridView

centity-framework

I try to explain better using an example:

  • I create the class Product with attibutes like that:

    private string _ProductCode = "";
    [DisplayName("ProductCode")]
    public String ProductCode
    {
       get { return _ProductCode; }
       set { _ProductCode = value; OnPropertyChanged("ProductCode"); }
    }
    
  • the class Product implements the interfaces: INotifyPropertyChanged, IEditableObject

  • I create the class ProductList that has the following property:

    public List<Product> Products { get; set; }
    
  • I bind the class Product in a DataGridView control using the DataSource property

    MyGridView.DataSource = ProductList.Products;
    
  • I have the table ProductListTable on db SqlServer that has more column than the class Product

  • When I push the button "Save" on my form I'd would like to save the ProductList on ProductListTable

I'm really confusing about the way to follow … I have to use Link 2 Sql, Entity Framework? I'm searching for something simple for a small project, but using POCO classes for rapresenting the data layer.

Now how I should proceed for linking class to DB table?

Best Answer

You can use Dapper. It is really simple, it boils down to having right sql. Here is example. PS: Use NuGet in VS and search for Dapper.

using(var con = new SqlConnection(connectionString))
{
    con.Open();
    con.Execute(
        @"insert ProductListTable(ProductCode, ...) values (@ProductCode, ...)",
        ProductList.Products
    );
}