如何创建集合(1:n)关系 [英] how to create collection (1:n) relation

查看:83
本文介绍了如何创建集合(1:n)关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Windows Store应用程序(WinRT)中实现SQLite数据库. 我想在两个表之间建立关系(1:n) 书(1)-章(n)

I'm implementing SQLite database in my Windows Store application (WinRT). I want to relation between two tables (1:n) Book (1) - Chapter (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不支持直接无法实现的任何事情 >映射到数据库.有关原因,请参见此处:

Just to follow up on my comment with a bit more research - SQLite-net doesn't support anything which can't be directly mapped to the database. See here for why:

ORM可以采用.NET类定义并将其转换为SQL表定义. (大多数ORM朝着另一个方向发展.)它是通过检查类的所有公共属性来完成的,并辅以可用于指定列详细信息的属性.

The ORM is able to take a .NET class definition and convert it to a SQL table definition. (Most ORMs go in the other direction.) It does this by examining all public properties of your classes and is assisted by attributes that you can use to specify column details.

您可以考虑使用其他ORM来实际访问您的数据(我使用 Vici Coolstorage )这就是您要执行的操作,或者只是从类中删除List<Chapters>并向Chapters类添加一个BookID字段.数据库就是这样表示的.

You can look into using a different ORM to actually access your data (I use Vici Coolstorage), if that's what you're trying to do, or simply remove the List<Chapters> from your class and add a BookID field to the Chapters class. That's how the database would represent it.

出于使用它的目的,您可以将以下其中之一添加到您的班级中:

For purposes of working with it, you could add one of these to your class:

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); 
  } 
}

这至少会让您轻松地拉出列表,尽管这样做会很慢,因为它每次访问数据库时都会命中数据库.

That would at least let you pull the list easily, although it would be slow because it hits the database every time you access it.

这篇关于如何创建集合(1:n)关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆