我正在开发一个Xamarin应用程序作为学习练习,但我不能为我的生活让关系正确映射/按预期工作。 Iridium是我选择的ORM,因为它可能比标准SQLite更好地支持关系和自定义类型。 我已经创建了一个单独的控制台应用程序来尝试调试这个,但又一次碰壁了。任何人都可以帮助指出我错过了什么?或者是否有一些基本的东西我一直忽略了铱/关系/类型或ORM?
NuGet:iridium.db.sqlite
class Model
{
[Column.PrimaryKey(AutoIncrement = true)]
private int _ID;
public int ID { get { return _ID; } set { _ID = value; } }
[Column.Null]
public string Name { get; set; }
private List<ChildModel> _object;
[Relation.OneToMany]
private IEnumerable<ChildModel> _Objects
{
get { return _object; }
set { _object = value.ToList(); }
}
public List<ChildModel> Objects
{
get { return _object; }
set { _object = value; }
}
public Model()
{
_object = new List<ChildModel>();
}
}
class ChildModel
{
[Column.PrimaryKey(AutoIncrement = true)]
private int _ID;
public int ID { get { return _ID; } set { _ID = value; } }
[Column.Null]
public string Name { get; set; }
public ChildModel()
{
}
}
class Program
{
static void Main(string[] args)
{
var dbContext = new StorageContext(new SqliteDataProvider("mydbTest.sqlite"));
// Create tables (if they don't exist) yet
dbContext.CreateTable<Model>();
dbContext.CreateTable<ChildModel>();
//generate test data
Model model = new Model {Name ="Test" };
model.Objects.Add(new ChildModel { Name = "first" });
model.Objects.Add(new ChildModel { Name = "second" });
model.Objects.Add(new ChildModel { Name = "third" });
//Save Test Data in DB.
dbContext.Insert(model, obj => obj.Objects);
//TODO: read test data once we know it stores properly...
}
}
答案 0 :(得分:1)
您的模型类应该简单得多。另外,ChildModel需要一个指向父模型的外键:
class Model
{
[Column.PrimaryKey(AutoIncrement = true)]
public int ID { get;set; }
[Column.Null]
public string Name { get; set; }
[Relation.OneToMany(ForeignKey="ParentID")
public List<ChildModel> Objects {get;set;} = new List<ChildModel>();
}
class ChildModel
{
[Column.PrimaryKey(AutoIncrement = true)]
public int ID { get;set; }
public int ParentID {get;set;}
[Column.Null]
public string Name { get; set; }
}