Search code examples
c#entity-frameworkxamarinsqlite-netsqlite-net-extensions

Automatically set entitykey in One-to-One relationship with SQLite-Net extensions


In a Xamarin project using SQLite-Net extensions, I have two entities: Project and ProjectSettings. These entities have a one-to-one relationship. The Project entity has an auto-increment Id. When I initially save a project, the Id of the Project is automatically set. This is working fine.

public class Project
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    [OneToOne(CascadeOperations = CascadeOperation.All)]
    public ProjectSettings Settings { get; set; }
}

For the ProjectSettings, I would expect that the ProjectId is the same as the Id in the Project table (ForeignKey).

public class ProjectSettings
{
    [PrimaryKey, ForeignKey(typeof(Project))]
    public int ProjectId { get; set; }
}

However, the ProjectID in the ProjectSettings table is 0 after persisting the Project. I am persisting the project using database.InsertOrReplaceWithChildren(project). Project and ProjectSettings both have their Id=0 when calling this method.

As I am quite new to SQLite-Net, I am wondering if I am using the annotations incorrectly or if manual steps are necessary to set the key of the ProjectSettings correctly?


Solution

  • You can't use InsertOrReplace with an AutoIncrement primary key with SQLite.Net. It will always override the object with ID 0. Either use another insert method, or manually assign the primary key.