当前位置: 首页 > news >正文

C# Android 开发中使用 Sqlite.NET ORM

开发环境:VS2015 Xamarin

Sqlite.NET ORM 不就相当于 Entiry Framework For Xamarin 吗? 相当于用 C# 开发安卓程序访问 Sqlite 可以使用 EF 了, 还支持CodeFirst ,再加上 linq,简直不要太帅啊。

亲测通过,转载原文,懒得翻译,备忘。 有兴趣的见官方:https://developer.xamarin.com/guides/android/application_fundamentals/data/part_3_using_sqlite_orm/

Using SQLite.NET

The SQLite.NET library that Xamarin recommends is a very basic ORM that lets you easily store and retrieve objects in the local SQLite database on an Android device. ORM stands for Object Relational Mapping – an API that lets you save and retrieve "objects" from a database without writing SQL statements.

There are two ways to include SQLite.NET in your Xamarin project:

  • NuGet – The code is available as a SQLite.net PCL NuGet package,  which supports a variety of platforms including iOS, Android, and Windows.

     PM> Install-Package sqlite-net-pcl

  • Component Store – SQLite.NET is available for iOS and Android from the Xamarin Component Store.

Regardless of which method you use to include SQLite.NET in your application, the code to use it the same. Once you have the SQLite.NET library available, follow these three steps to use it to access a database:

  1. Add a using statement – Add the following statement to the C#  files where data access is required:

    using SQLite;

     

  2. Create a Blank Database – A database reference can be created by passing the file path the SQLiteConnection class constructor. You do not need to check if the file already exists – it will automatically be created if required, otherwise the existing database file will be opened.

    var db = new SQLiteConnection (dbPath);

     

    The dbPath variable should be determined according the rules discussed earlier in this document.

  3. Save Data – Once you have created a SQLiteConnection object, database commands are executed by calling its methods, such as CreateTable and Insert like this:

    db.CreateTable<Stock> ();
    db.Insert (newStock); // after creating the newStock object

     

  4. Retrieve Data – To retrieve an object (or a list of objects) use the following syntax:

    var stock = db.Get<Stock>(5); // primary key id of 5
    var stockList = db.Table<Stock>();

     

Basic Data Access Sample

The following code sample shows an entire database interaction using the SQLite.NET library to encapsulate the underlying database access. It shows:

  1. Creating the database file

  2. Inserting some data by creating objects and then saving them

  3. Querying the data

You'll need to include these namespaces:

using SQLite; // from the github SQLite.cs class

The last one requires that you have added SQLite to your project. Note that the SQLite database table is defined by adding attributes to a class (the Stock class) rather than a CREATE TABLE command.

[Table("Items")]
public class Stock {
    [PrimaryKey, AutoIncrement, Column("_id")]
    public int Id { get; set; }
    [MaxLength(8)]
    public string Symbol { get; set; }
}
public static void DoSomeDataAccess () {
       Console.WriteLine ("Creating database, if it doesn't already exist");
   string dbPath = Path.Combine (
        Environment.GetFolderPath (Environment.SpecialFolder.Personal),
        "ormdemo.db3");
   var db = new SQLiteConnection (dbPath);
   db.CreateTable<Stock> ();
   if (db.Table<Stock> ().Count() == 0) {
        // only insert the data if it doesn't already exist
        var newStock = new Stock ();
        newStock.Symbol = "AAPL";
        db.Insert (newStock);
        newStock = new Stock ();
        newStock.Symbol = "GOOG";
        db.Insert (newStock);
        newStock = new Stock ();
        newStock.Symbol = "MSFT";
        db.Insert (newStock);
    }
    Console.WriteLine("Reading data");
    var table = db.Table<Stock> ();
    foreach (var s in table) {
        Console.WriteLine (s.Id + " " + s.Symbol);
    }
}

 

Using the [Table] attribute without specifying a table name parameter will cause the underlying database table to have the same name as the class (in this case, "Stock"). The actual table name is important if you write SQL queries directly against the database rather than use the ORM data access methods. Similarly the [Column("_id")] attribute is optional, and if absent a column will be added to the table with the same name as the property in the class.

SQLite Attributes

 

Common attributes that you can apply to your classes to control how they are stored in the underlying database include:

  • [PrimaryKey] – This attribute can be applied to an integer property to force it to be the underlying table's primary key. Composite primary keys are not supported.

  • [AutoIncrement] – This attribute will cause an integer property's value to be auto-increment for each new object inserted into the database

  • [Column(name)] – Supplying the optional name parameter will override the default value of the underlying database column's name (which is the same as the property).

  • [Table(name)] – Marks the class as being able to be stored in an underlying SQLite table. Specifying the optional name parameter will override the default value of the underlying database table's name (which is the same as the class name).

  • [MaxLength(value)] – Restrict the length of a text property, when a database insert is attempted. Consuming code should validate this prior to inserting the object as this attribute is only 'checked' when a database insert or update operation is attempted.

  • [Ignore] – Causes SQLite.NET to ignore this property. This is particularly useful for properties that have a type that cannot be stored in the database, or properties that model collections that cannot be resolved automatically be SQLite.

  • [Unique] – Ensures that the values in the underlying database column are unique.

Most of these attributes are optional, SQLite will use default values for table and column names. You should always specify an integer primary key so that selection and deletion queries can be performed efficiently on your data.

More Complex Queries

 

The following methods on SQLiteConnection can be used to perform other data operations:

  • Insert – Adds a new object to the database.

  • Get<T> – Attempts to retrieve an object using the primary key.

  • Table<T> – Returns all the objects in the table.

  • Delete – Deletes an object using its primary key.

  • Query<T> – Perform an SQL query that returns a number of rows (as objects).

  • Execute – Use this method (and not Query) when you don't expect rows back from the SQL (such as INSERT, UPDATE and DELETE instructions).

Getting an object by the primary key

 

SQLite.Net provides the Get method to retrieve a single object based on its primary key.

var existingItem = db.Get<Stock>(3);

Selecting an object using Linq

 

Methods that return collections support IEnumerable<T> so you can use Linq to query or sort the contents of a table. The entire table is loaded into a collection prior to the Linq query executing, so performance of these queries could be slow for large amounts of data.

The following code shows an example using Linq to filter out all entries that begin with the letter "A":

var apple = from s in db.Table<Stock>()
    where s.Symbol.StartsWith ("A")
    select s;
Console.WriteLine ("-> " + apple.FirstOrDefault ().Symbol);

 

Selecting an object using SQL

 

Even though SQLite.Net can provide object-based access to your data, sometimes you might need to do a more complex query than Linq allows (or you may need faster performance). You can use SQL commands with the Query method, as shown here:

var stocksStartingWithA = db.Query<Stock>("SELECT * FROM Items WHERE Symbol = ?", "A");
foreach (var s in stocksStartingWithA) {
    Console.WriteLine ("a " + s.Symbol);
}

 

ℹ️

Note: When writing SQL statements directly you create a  dependency on the names of tables and columns in your database, which  have been generated from your classes and their attributes. If you  change those names in your code you must remember to update any  manually written SQL statements.

Deleting an object

 

The primary key is used to delete the row, as shown here:

var rowcount = db.Delete<Stock>(someStock.Id); // Id is the primary key

You can check the rowcount to confirm how many rows were affected (deleted in this case).

Using SQLite.NET with Multiple Threads

 

SQLite supports three different threading modes: Single-thread, Multi-thread, and Serialized. If you want to access the database from multiple threads without any restrictions, you can configure SQLite to use the Serialized threading mode. It's important to set this mode early in your application (for example, at the beginning of the OnCreate method).

To change the threading mode, call SqliteConnection.SetConfig. For  example, this line of code configures SQLite for Serialized mode:

SqliteConnection.SetConfig(SQLiteConfig.Serialized);

The Android version of SQLite has a limitation that requires a few more  steps. If the call to SqliteConnection.SetConfig produces a SQLite  exception such as library used incorrectly, then you must use the  following workaround:

  1. Link to the native libsqlite.so library so that the sqlite3_shutdown and sqlite3_initialize APIs are made  available to the app:

    [DllImport("libsqlite.so")]
    internal static extern int sqlite3_shutdown();  [DllImport("libsqlite.so")] internal static extern int sqlite3_initialize();
  2. At the very beginning of the OnCreate method, add this code to shutdown SQLite, configure it for Serialized mode, and reinitialize SQLite:

    sqlite3_shutdown();
    SqliteConnection.SetConfig(SQLiteConfig.Serialized); sqlite3_initialize();

This workaround also works for the Mono.Data.Sqlite library. For more  information about SQLite and multi-threading, see  SQLite and Multiple Threads.

转载于:https://www.cnblogs.com/nanfei/p/7250688.html

相关文章:

  • 大数据到底怎么学:数据科学概论与大数据学习误区
  • 选项卡TAB
  • 你想快速成为大数据工程师?
  • 【USACO4.2】草地排水Drainage Ditches(最大流)
  • 如何快速学习大数据挖掘分析(个人观点)
  • 人工智能与大数据开发的12个注意事项
  • GuozhongCrawler系列教程 (2) CrawTaskBuilder具体解释
  • 如何利用数据挖掘告别单身
  • 为何大数据开发师的工资能这么高
  • BZOJ2242 SDOI2011 计算器
  • 关于反爬虫,看完这篇文章就够了
  • 使用.NET Reflector 查看Unity引擎里面的DLL文件
  • 大数据从业者应该知道的开源工具(全)
  • python--内置函数
  • 什么是大数据挖掘技术
  • 收藏网友的 源程序下载网
  • angular2 简述
  • Docker 笔记(2):Dockerfile
  • JAVA SE 6 GC调优笔记
  • JS基础之数据类型、对象、原型、原型链、继承
  • mockjs让前端开发独立于后端
  • node 版本过低
  • rabbitmq延迟消息示例
  • 阿里中间件开源组件:Sentinel 0.2.0正式发布
  • 反思总结然后整装待发
  • 仿天猫超市收藏抛物线动画工具库
  • 给初学者:JavaScript 中数组操作注意点
  • 工程优化暨babel升级小记
  • 海量大数据大屏分析展示一步到位:DataWorks数据服务+MaxCompute Lightning对接DataV最佳实践...
  • 解决iview多表头动态更改列元素发生的错误
  • 近期前端发展计划
  • 入口文件开始,分析Vue源码实现
  • 提醒我喝水chrome插件开发指南
  • 突破自己的技术思维
  • 王永庆:技术创新改变教育未来
  • No resource identifier found for attribute,RxJava之zip操作符
  • 2017年360最后一道编程题
  • #QT(TCP网络编程-服务端)
  • #Ubuntu(修改root信息)
  • %3cscript放入php,跟bWAPP学WEB安全(PHP代码)--XSS跨站脚本攻击
  • (poj1.3.2)1791(构造法模拟)
  • (三)elasticsearch 源码之启动流程分析
  • (四)Controller接口控制器详解(三)
  • (算法)求1到1亿间的质数或素数
  • (原創) 如何使用ISO C++讀寫BMP圖檔? (C/C++) (Image Processing)
  • (转)EOS中账户、钱包和密钥的关系
  • (转载)跟我一起学习VIM - The Life Changing Editor
  • .MyFile@waifu.club.wis.mkp勒索病毒数据怎么处理|数据解密恢复
  • .NET 发展历程
  • .NET6 开发一个检查某些状态持续多长时间的类
  • .NET简谈设计模式之(单件模式)
  • .NET设计模式(7):创建型模式专题总结(Creational Pattern)
  • @entity 不限字节长度的类型_一文读懂Redis常见对象类型的底层数据结构
  • @requestBody写与不写的情况
  • [3300万人的聊天室] 作为产品的上游公司该如何?