如何使用SQLite创建关系(外键)

时间:2019-04-08 12:26:56

标签: c# xamarin xamarin.forms sqlite

我正在尝试在SQLite中与我的表创建关系(我目前正在使用Xamarin.Forms),但未获得预期的结果,而是添加了数据注释[ForeignKey(typeof(UserLocal))] 但是我没有在BD中创建关系,这是怎么回事?我的BD仅在建立索引关系,而没有将它们与外键相关

Browser SQLite

对于与数据库的连接,我创建了一个接口,该接口获取Android和iOS中的路由,然后管理我的INSERT,UPDATE,DELETE等……我通过DataService.CS服务来实现。

机器人:

[assembly: Xamarin.Forms.Dependency(typeof(PathService))]
namespace AppValora.Droid.Implementation
{
    public class PathService : IPathService
    {
        public string GetDatabasePath()
        {              
            string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
            var directoryPath = Path.Combine(path, "Valora/Databases");
            if (!Directory.Exists(directoryPath))
            {
                try
                {

                    Directory.CreateDirectory(directoryPath);
                }
                catch (Exception ex)
                {

                }
            }
            return Path.Combine(directoryPath, "Valora.db3");
        }
    }
}

iOS:

[assembly: Dependency(typeof(PathService))]
namespace AppValora.iOS.Implementation
{
    public class PathService : IPathService
    {
        public string GetDatabasePath()
        {
            string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string libFolder = Path.Combine(docFolder, "..", "Library");

            if (!Directory.Exists(libFolder))
            {
                Directory.CreateDirectory(libFolder);
            }

            return Path.Combine(libFolder, "Valora.db3");
        }
    }
}

DATASERVICE.CS:

#region Servicios
private SQLiteAsyncConnection connection;
private DialogService dialogService;       
#endregion

#region Constructor
public DataService()
{
    dialogService = new DialogService();
    OpenOrCreateDB();
}
#endregion

private async Task OpenOrCreateDB()
{
    var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Storage);

    if (status != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
    {
        if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync((Plugin.Permissions.Abstractions.Permission.Storage)))
        {
            await dialogService.ShowMessage("!ATENCIÓN!", "Valora necesita el permiso de archivos para este proceso.");
        }

        var results = await CrossPermissions.Current.RequestPermissionsAsync((Plugin.Permissions.Abstractions.Permission.Storage));
        //Best practice to always check that the key exists
        if (results.ContainsKey(Plugin.Permissions.Abstractions.Permission.Storage))
            status = results[Plugin.Permissions.Abstractions.Permission.Storage];
    }

    if (status == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
    {
        //CONSULTO PATH
        var databasePath = DependencyService.Get<IPathService>().GetDatabasePath();
        //CREO LA CONEXION
        this.connection = new SQLiteAsyncConnection(databasePath);
        //CREACION DE TABLAS
        await connection.CreateTableAsync<UserLocal>().ConfigureAwait(false);
        await connection.CreateTableAsync<Companie>().ConfigureAwait(false);
    }
    else if (status != Plugin.Permissions.Abstractions.PermissionStatus.Unknown)
    {

    }    

    public async Task Insert<T>(T model)
    {
        await this.connection.InsertAsync(model);
    }
}

DataService除了建立连接外,还创建了要在其中生成关系的表。数据模型如下...

USERLOCAL.CS:

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

    public int IdLogin { get; set; }
    public string Token { get; set; }             
    public string Nombre { get; set; }
    public string Rut { get; set; }
    public bool Recordado { get; set; }
    public string Password { get; set; }

    [OneToMany]
    public List<Companie> Companies { get; set; }
}

COMPANIE.CS:

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

    public int IdLogin { get; set; }
    public string Nombre { get; set; }
    public bool Principal { get; set; }
    public bool ExternalCorp { get; set; }
    public bool IsCorporate { get; set; }

    [ForeignKey(typeof(UserLocal))]
    public int IdUser { get; set; }

    [ManyToOne]
    public UserLocal UserLocal { get; set; }
}

接下来,下面显示了如何在表中插入记录的代码,我认为这是我错的地方,因为我无法创建关系

VIEWMODEL.CS:

ListaCompanie.Clear();          

// I WALK THE NUMBER OF COMPANIES THAT I WANT TO ADD
foreach (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
        IdUser = loginResponse.Id,
    };

    ListaCompanie.Add(companie);

    await dataService.Insert(companie);
}

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,
};

await dataService.Insert(user);

为什么不生成这些关系?如何将表与SQLite相关联?我究竟做错了什么?我正在使用具有MVVM架构模式的Xamarin.Forms,对我有帮助吗?

1 个答案:

答案 0 :(得分:0)

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

public class UserLocal
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public int IdLogin { get; set; }
    public string Token { get; set; }             
    public string Nombre { get; set; }
    public string Rut { get; set; }
    public bool Recordado { get; set; }
    public string 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 ADD
foreach (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);
}