簡體   English   中英

如何創建集合(1:n)關系

[英]how to create collection (1:n) relation

我正在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

我究竟做錯了什么 ?

僅僅通過更多研究來跟進我的評論 - SQLite-net不支持任何無法直接映射到數據庫的內容。 這里是為什么:

ORM能夠獲取.NET類定義並將其轉換為SQL表定義。 (大多數ORM都朝另一個方向發展。)它通過檢查類的所有公共屬性來完成此操作,並由可用於指定列詳細信息的屬性輔助。

您可以考慮使用不同的ORM來實際訪問您的數據(我使用Vici 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); 
  } 
}

這至少可以讓你輕松地拉出列表,雖然它會很慢,因為它每次訪問時都會訪問數據庫。

看一下SQLite-Net Extensions 它通過使用反射在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; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM