PetaPoco - How do I turn off auto zoom?

I ran into this error when trying to do an insert:

Cannot insert null value in column "Id"

It looks like PetaPoco by default assumes that the Id column is automatically incremented, so even if you provide a value, it will try to insert null instead. I found a bug for the problem here: https://dnntracker.atlassian.net/browse/DNN-23217 .

I am using PetaPoco T4 template to generate my database classes. I created a partial class, applied data annotation to turn off auto-increment:

[PrimaryKey("Id", autoIncrement = false)]
public partial class Blah : DatabaseDB.Record<Database.Blah>
{
}

      

However, this doesn't seem to have any effect. PetaPoco still tries to insert null for the Id column when I give an integer.

+3


source to share


1 answer


I agree. This is really weird and confusing behavior because their API doesn't always use this attribute .

There are two ways to make it work.

One is not using an attribute in your example, and using an overloaded method with an autoIncrement parameter and setting it to false . Here's a complete example:

// Create a PetaPoco database object
var db = new PetaPoco.Database("ConnectionSt");

// Create an article
var a = new Article
{
    article_id = 152,
    title = "My new article",
    content = "PetaPoco was here",
    date_created = DateTime.UtcNow
};

// Insert it by turning off auto-increment
db.Insert("articles", "article_id", false, a);

      



Another is to use the insert method, which takes an object as a parameter:

// Create an article
var a = new Articles
{
    article_id = 1111,
    title = "My new article",
    content = "PetaPoco was here",
    date_created = DateTime.UtcNow
};

// Insert it by using the insert method that will use the attribute!
db.Insert(a);

      

The overload that takes an object as a parameter is the only one that uses the attribute PrimaryKey

internally, and it should work like a charm in your scenario.

+6


source







All Articles