Skip to content Skip to sidebar Skip to footer

How To Create Relationships With Sqlite (foreign Key)

I'm trying to create relationships with my tables in SQLite (I'm currently working with Xamarin.Forms), but I'm not getting the expected result, adding the Data Annotations [Fore

Solution 1:

If you are using SQLite.Net.Extensions for creating the relationships then you need to set the CascadeOperations like so:

publicclassUserLocal
{
    [PrimaryKey, AutoIncrement]
    publicint Id { get; set; }
    publicint IdLogin { get; set; }
    publicstring Token { get; set; }             
    publicstring Nombre { get; set; }
    publicstring Rut { get; set; }
    publicbool Recordado { get; set; }
    publicstring Password { get; set; }

    // THIS BIT HERE 
    [OneToMany(CascadeOperations = CascadeOperation.All)]
    public List<Companie> Companies { get; set; }
}

The other thing is if you are using this library then you can insertWithChildren to create the relationship like so:

var user = new UserLocal
{
    IdLogin = loginResponse.Id,
    Nombre = loginResponse.Name,
    Recordado = Settings.Recordado,
    Rut = loginResponse.Rut,
    Token = loginResponse.Token,
    Password = GetSHA1(Settings.Password),
    Companies = ListaCompanie,
};

// I WALK THE NUMBER OF COMPANIES THAT I WANT TO ADDforeach (var item in loginResponse.Companies)
{
    var companie = new Companie
    {
        IdLogin = item.Id,
        Nombre = item.Name,
        ExternalCorp = item.ExternalCorp,
        IsCorporate = item.IsCorporate,
        Principal = item.Principal,
        //CLAVE FORANEA
        UserLocal = user,
        // You dont need to set this as it will be assigned in InsertWithChildren// IdUser = loginResponse.Id,
    };

    ListaCompanie.Add(companie);

    await dataService.InsertWithChildren(companie);
}

Post a Comment for "How To Create Relationships With Sqlite (foreign Key)"