繁体   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