如何与SQLite建立关系(外键)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何与SQLite建立关系(外键)相关的知识,希望对你有一定的参考价值。
我正在尝试在SQLite中创建与我的表的关系(我目前正在使用Xamarin.Forms),但是我没有得到预期的结果,添加数据注释[ForeignKey(typeof(UserLocal))]
但是我没有在我的BD中创建关系, 这是怎么回事?我的BD只执行索引关系,但它没有将它们与外键相关联
为了连接到我的数据库,我创建了一个接口,在android和ios中获取路由,然后管理我的INSERT,UPDATE,DELETE等...我是从DataService.CS服务中做到的。
ANDROID:
[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,对我有什么帮助?
答案
如果你使用SQLite.Net.Extensions创建关系,那么你需要像这样设置CascadeOperations
:
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;
另一件事是如果你使用这个库,那么你可以insertWithChildren
创建这样的关系:
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);
以上是关于如何与SQLite建立关系(外键)的主要内容,如果未能解决你的问题,请参考以下文章