Search code examples
c#npoco

NPOCO Save not working only for specific model


I have a method for saving using NPOCO which is working fine except for one model.

public bool Upsert<T>(T record, string message)
        {
            try
            {
                using (var db = new Database(GetConnStr(), DatabaseType.SqlServer2008))
                {
                    db.Save(record);
                    return true;
                }
            }
            catch (Exception x)
            {
                //log exception
                return false;
            }
        }

This code works and I am using with several models. However with the following model, it's not saving and not throwing any error:

[PrimaryKey("LoginName")]
public class TableName
{
    public string LoginName { get; set; }
    public string RealName { get; set; }
    public string Tag { get; set; }
}

I have debugged and stepped through the code and confirmed the model contains data, the save method is hit and no exception is thrown. I have changed the model name to a wrong value and gets the right error invalid object name. However when I changed it back to the correct name the data is not saved and no error is thrown. I've manually inserted same record into the database using management studio without error (just to be sure no hidden DB errors).

UPDATE: For whatever reason it seems NPOCO is not mapping LoginName. I came to this conclusion by:

  1. Using NPOCO SingleById which throws the following error:

    "No mapping exists from object type <>f__AnonymousType42`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] to a known managed provider native type."

  2. Used the Insert method instead of the Save. When I do that I get the error:

    "Cannot insert the value NULL into column 'LoginName', table 'TableName'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."

even though the model has all the values, when I inspect it through the debugger.

I suspect the save does not throw error because it's an upsert.


Solution

  • Try changing your Primary Key definition to

    [PrimaryKey("LoginName", AutoIncrement=false)]
    

    Since LoginName is not an auto increment field, it can't add the record. The default is True for AutoIncrement.