Is there any requirement for model class in SQLite database?

假装没事ソ 提交于 2021-02-08 09:52:54

问题


I am writing code using LINQ to SQLite on UWP.

To my understanding, models are templates of rows of the tables in the database. The documentations about SQLite barely mention the restrictions of the models, or how the models are converted into rows of tables. The sample codes usually provide only simple cases with primary types.

My questions are:

  1. Is there any difference between a database model class and a normal class. I find at least in this example(which is a nice one, by the way),

The model class members are decorated with attributes to indicate keys.

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

Is this attribute necessary for the class? Is there any other similar tricks?

  1. If there is any general difference between a model class and a normal class, is it required by SQLite or is it required by LINQ?

  2. How are complex data stored in database, such as List<> in a model class. Are properties treated as methods or as fields, and do properties take a column in the table?


回答1:


  1. The only difference is that you set some attributes on the database model so SQLite would know which is the primary key, which fields should be ignored, etc. But you can reuse that class from any part of the code. You could even have a model that is used by the database and the UI for data binding, but it's not recommended.
  2. LINQ doesn't require any attributes, they are used only by SQLite.
  3. For storing a List<> you can use SQLite Extensions

This is an example from their site:

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


来源:https://stackoverflow.com/questions/41961477/is-there-any-requirement-for-model-class-in-sqlite-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!