如何创建集合(1:N)关系(how to create collection (1:n) relat

2019-08-02 03:02发布

我在我的Windows Store应用程序(WinRT的)实施SQLite数据库。 我想这两个表之间的关系(1:N),图书(1) - 第一章(N)

class Book
{
    [SQLite.AutoIncrement, SQLite.PrimaryKey]
    public int Id { get; set; }
    public String Title { get; set; }
    public String Description { get; set; }
    public String Author { get; set; }
    public List<Chapter> Chapters { get; set; }

    public Book() 
    {
        this.Chapeters = new List<Chapter>();
    }
}

我得到

-       $exception  {"Don't know about     System.Collections.Generic.List`1[Audioteka.Models.Chapter]"}    System.Exception {System.NotSupportedException}

+       [System.NotSupportedException]  {"Don't know about System.Collections.Generic.List`1[Audioteka.Models.Chapter]"}    System.NotSupportedException

+       Data    {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
    HelpLink    null    string
    HResult -2146233067 int
+       InnerException  null    System.Exception
    Message "Don't know about System.Collections.Generic.List`1[Audioteka.Models.Chapter]"  string

我究竟做错了什么 ?

Answer 1:

只是跟进与多一点研究我的评论- SQLite的网不支持任何不能被直接映射到数据库中。 见这里的原因:

在ORM能够采取一个.NET类的定义,并将其转换为SQL表定义。 (大多数奥姆斯走在其他方向。)它通过检查你的类的所有公共属性做到这一点,并通过您可以使用指定列属性的详细信息协助。

你可以考虑使用不同的ORM实际访问您的数据(我用维西Coolstorage ),如果这就是你想要做什么,或者干脆删除List<Chapters>从你的类和添加BookID场的Chapters类。 这是该数据库将如何表现它。

对于使用它的目的,你可以添加这些到您的类之一:

List<Chapters> Chapters { 
  get { 
     return db.Query<Chapters> ("select * from Chapters where BookId = ?", this.Id); 
  } 
}

要么

List<Chapters> Chapters { 
  get { 
     return db.Query<Chapters>.Where(b => b.BookId == this.Id); 
  } 
}

这将至少让你轻松拉列表中,尽管因为它击中每次你访问它时的数据库这将是缓慢的。



Answer 2:

看看的SQLite-Net的扩展 。 它提供了通过使用反射在SQLite的-Net的顶部的复杂关系。

例如从网站中提取:

public class Stock
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [MaxLength(8)]
    public string Symbol { get; set; }

    [OneToMany]      // One to many relationship with Valuation
    public List<Valuation> Valuations { get; set; }
}

public class Valuation
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    [ForeignKey(typeof(Stock))]     // Specify the foreign key
    public int StockId { get; set; }
    public DateTime Time { get; set; }
    public decimal Price { get; set; }

    [ManyToOne]      // Many to one relationship with Stock
    public Stock Stock { get; set; }
}


文章来源: how to create collection (1:n) relation