我决定在Xamarin.Android中实现数据库,该数据库将数据存储在设备上,并且偶尔会从服务器获取数据。无论如何,我想从头开始创建数据库,如果它不存储表。在构造函数崩溃中创建多对多表,因为第二个表尚未创建
我的问题是我有用于创建新表的模型,但这些模型通过多对多的关系连接起来,并在第一次创建表时崩溃事务。
我知道这与约束有关,但我不知道如何重构应用程序以避免这种情况。我无法直接找到与此相关的任何回复。
有什么想法?
class Database
{
private SQLiteConnection _connection;
public Database()
{
_connection = new SQLite().GetConnection();
LogHelper.CustomLog("SQL Created");
_connection.BeginTransaction();
_connection.CreateTable<Dish>(); //there is the issue
_connection.CreateTable<Ingredient>();
_connection.Commit();
LogHelper.CustomLog("SQL DBs created");
AddIngredient(new Ingredient() { Id = 1, Name = "apple", Vegetarian = false, GlutenFree = false });
AddDish(new Dish() { Id = 1, Calories = "23", Desc = "test", Name = "oranges", Time = 30, Ingredients = GetIngredientList() });
}
}
public class Dish
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public string Desc { get; set; }
public int Time { get; set; }
//public string Rating { get; set; }
public string Calories { get; set; }
[ForeignKey(typeof(Ingredient))]
public int IngredientId { get; set; }
[ManyToMany(typeof(Dish))]
public List<Ingredient> Ingredients { get; set; }
public override string ToString()
{
return string.Format("[Dish: Id={0}, Name={1}, Desc={2}, Time={3},
Ingredients={4}, Calories={6}]",
Id, Name, Desc, Time, Ingredients, Calories);
}
}
public class Ingredient
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public bool Vegetarian { get; set; }
public bool GlutenFree { get; set; }
[ForeignKey(typeof(Dish))]
public int DishId { get; set; }
[ManyToMany(typeof(Ingredient))]
public List<Dish> Dishes { get; set; }
}
更改我仍然无法创建表后。 https://ibb.co/gdboqQ – Perisher
@Perisher错误似乎与此问题有关:https://github.com/praeclarum/sqlite-net/issues/553 – apineda