问题
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:
- 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?
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?
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:
- 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.
- LINQ doesn't require any attributes, they are used only by SQLite.
- 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