Inserting Data

Inserting data with the ORM is simple and straightforward.  To enable Insert behavior, you must first register the Entity type with the DataStore.  Registration needs to only happen once, and it typically done when you create the DataStore instance or shortly afterward.

store.AddType<Author>();

Once the type has been registered, you can insert an entity instance by simply passing it as a parameter to the Insert method.  The DataStore will know which table the instance should be inserted into based on the earlier type registration.

var author = new Author
{
    ID = 3,
    Name = "John Doe"
};
store.Insert(author);

If your database was generated with a KeyScheme of Identity and an int PrimaryKey field with auto-increment enabled, then the ORM will update the entity instance with the generated primary key for you.

// entity definition
[Entity(KeyScheme = KeyScheme.Identity)]
public class Author
{
    [Field(IsPrimaryKey = true)]
    public int ID { get; set; }

    [Field]
    public string Name { get; set; }
}


// some time later in your code
var author = new Author
{
    Name = "John Doe"
};

var oldID = authorID; // this will be the default (0)
store.Insert(author);
var newID = authorID; // this will be the new value assigned by the database engine



If you use code-first methodology and let ORM create the DataStore for you, the Entity's underlying table will automatically have AUTO INCREMENT added to the primary key field definition (assuming you used the Identity key scheme and an integer ID field).  If you're using database-first, you will have to either verify that your database is set to auto-increment or you will have to add key generation to your own code.

Last edited Sep 11, 2012 at 2:25 PM by ctacke, version 7

Comments

No comments yet.