【问题标题】:Is there any requirement for model class in SQLite database?SQLite 数据库中对模型类有什么要求吗?
【发布时间】:2017-06-17 02:52:21
【问题描述】:

我正在 UWP 上使用 LINQ to SQLite 编写代码。

据我了解,模型是数据库中表格行的模板。关于 SQLite 的文档几乎没有提到模型的限制,或者模型如何转换为表的行。示例代码通常只提供具有主要类型的简单案例。

我的问题是:

  1. 数据库模型类和普通类有什么区别吗?我至少在this example 中找到了(顺便说一句,这是一个不错的),

模型类成员用属性修饰来表示键。

internal class Person
{
    /// <summary>
    /// Gets or sets the identifier.
    /// </summary>
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    ....
}

这个属性对类来说是必需的吗?还有其他类似的技巧吗?

  1. 如果模型类和普通类有什么一般的区别,是SQLite需要还是LINQ需要?

  2. 复杂数据如何存储在数据库中,例如模型类中的List&lt;&gt;。属性是被视为方法还是字段,属性是否在表中占用一列?

【问题讨论】:

    标签: c# database linq sqlite uwp


    【解决方案1】:
    1. 唯一的区别是你在数据库上设置了一些属性 模型,以便 SQLite 知道哪个是主键,哪个字段 应该被忽略,等等。但是您可以从任何部分重用该类 的代码。你甚至可以有一个模型被 数据库和数据绑定的 UI,但不建议这样做。
    2. LINQ 不需要任何属性,它们仅供 SQLite 使用。
    3. 为了存储一个列表你可以使用SQLite Extensions

    这是他们网站上的一个例子:

    public class Stock
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        [MaxLength(8)]
        public string Symbol { get; set; }
    
        [OneToMany(CascadeOperations = CascadeOperation.All)]      // 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; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多