Search code examples
c#.netsimple.data

Cannot insert a record with Simple.Data


I am using Simple.Data and I receive the following error at the last line when trying to run the code below: An unhandled exception of type 'System.ArgumentException' occurred in System.Core.dll.

    var db = Database.OpenConnection(ConnectionString);
    var product = db.DimDistrict.FindByDistrict("HOUSE");
    //db.FunnelQuotes.Insert(
    //    Company: funnelQuotes[0].Company,
    //    Opportunity: funnelQuotes[0].Opportunity,
    //    QuoteNumber: funnelQuotes[0].QuoteNumber,
    //    QuotedPrice: funnelQuotes[0].QuotedPrice);
    IList<FunnelQuote> retrows = db.FunnelQuotes.Insert(funnelQuotes).ToList();

Note that the commented out code works.

Edit: Added Class Definition

class FunnelQuote
{
    public string Company { get; set; }
    public string Opportunity { get; set; }
    public string QuoteNumber { get; set; }
    public float QuotedPrice { get; set; }
}

Solution

  • Since I couldn't find out why this wasn't working, I ended up just inserting the records one at a time in a foreach loop. However, I have discovered the source of the problem. It was as a result of the field size being too small, e.g., I had an NVARCHAR(10) data type in the database for one of the fields, but one of the rows had greater than 10 characters for that field. It turns out that the foreach loop was just hiding the error by truncating the field. So I thought I'd point out the behaviour of Simple.Data depending on how you do your insert.

    1. Insert with named parameters (I'm assuming it's the same if you insert by object): No error is thrown and the text field is truncated if it is too long.

      db.FunnelQuotes.Insert(
          Company: funnelQuotes[0].Company,
          Opportunity: funnelQuotes[0].Opportunity,
          QuoteNumber: funnelQuotes[0].QuoteNumber,
          QuotedPrice: funnelQuotes[0].QuotedPrice
      );
      
    2. Multi-insert without assigning result to a variable: System.InvalidOperationException is thrown with an InnerException that tells you that "String or binary data would be truncated."

      db.Quotes.Insert(funnelQuotes);
      
    3. Multi-insert, assigning result to a list as shown in the Simple.Data documentation: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException is thrown. The detail is "Cannot perform runtime binding on a null reference". However, in this case the data is still inserted! Any string fields that are too long will be truncated.

      List<FunnelQuote> retrows = db.Quotes.Insert(funnelQuotes).ToList();