我决定在Xamarin.Android中实现数据库,该数据库将数据存储在设备上,并偶尔从服务器获取数据。无论如何,如果它不存储表,我想从头开始创建数据库。
我的问题是我有用于创建新表的模型,但这些模型通过多对多关系与自身连接,并在首次尝试创建表时崩溃事务。
我知道这与约束相关,但我不知道如何重构app来避免这种情况。我直接找不到与此相关的任何回复。
有什么想法吗?
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; }
}
答案 0 :(得分:0)
查看SQLite-Net extensions的多对多关系。
文档中的引言:
使用外键无法表达多对多关系 其中一个实体,因为外键代表X对一 关系。相反,需要一个中间实体。这个 实体永远不会直接在应用程序中使用,但为了清晰起见 摇,SQLite-Net Extensions永远不会创建用户的表 没有明确定义。
答案 1 :(得分:0)
使用多对多关系,您需要一个中间实体。
尝试像这样定义您的实体:
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; }
[ManyToMany(typeof(DishIngredients))]
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; }
[ManyToMany(typeof(DishIngredients))]
public List<Dish> Dishes { get; set; }
}
public class DishIngredients
{
[ForeignKey(typeof(Dish))]
public int DishId { get; set; }
[ForeignKey(typeof(Ingredient))]
public int IngredientId { get; set; }
}