我试图添加一个可以为空的外键映射,但它不起作用。我知道数据库允许空值,因为在使用Datagrip时,我可以插入一个外键为空的新记录。我只是在尝试从一个用于安卓的Xamarin.Forms项目中插入(SQLite.SQLiteException:'Constraint')我的类看起来像这样的时候才得到这个错误:
public class Item
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
...
[ForeignKey(typeof(Location))]
public int LocationId { get; set; }
[ManyToOne]
public Location Location { get; set; }
}
public class Location
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
...
[OneToMany]
public List<Item> Items { get; set; }
}我的插件如下所示
//This will no work
var todoItem = new Item()
{
Name = "Test item " + DateTime.Now.TimeOfDay.ToString(),
Description = "Desc",
Location = null // I tried with and without this line
};
await App.Database.SaveItemAsync(todoItem);
//This will work
var todoItem = new Item()
{
Name = "Test item " + DateTime.Now.TimeOfDay.ToString(),
Description = "Desc",
LocationId = 1
};
await App.Database.SaveItemAsync(todoItem);知道我做错了什么吗?谢谢
发布于 2020-04-18 07:24:57
显然,这个库需要id字段可以为空,所以不是
[ForeignKey(typeof(Location))]
public int LocationId { get; set; }我应该使用
[ForeignKey(typeof(Location))]
public int? LocationId { get; set; }PS:在我的例子中,仅仅构建项目并没有使更改生效,我只能在重新构建项目后看到结果。(我是Xamarin的新手,可能我有一些配置错误……我希望)
https://stackoverflow.com/questions/61280583
复制相似问题