开发环境: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 StoreSQLite.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>(); // 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()]
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() == ) {
// 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.

C# Android 开发中使用 Sqlite.NET ORM的更多相关文章

  1. 在Android 开发中使用 SQLite 数据库笔记

    SQLite 介绍   SQLite 一个非常流行的嵌入式数据库,它支持 SQL 语言,并且只利用很少的内存就有很好的性能.此外它还是开源的,任何人都可以使用它.许多开源项目((Mozilla, PH ...

  2. Android 开发中使用 SQLite 数据库

    SQLite 介绍 SQLite 一个非常流行的嵌入式数据库,它支持 SQL 语言,并且只利用很少的内存就有很好的性能. 此外它还是开源的,任何人都可以使用它.许多开源项目((Mozilla, PHP ...

  3. 【转】Android开发中的SQLite事务处理,即beginTransaction()方法

    使用SQLiteDatabase的beginTransaction()方法可以开启一个事务,程序执行到endTransaction() 方法时会检查事务的标志是否为成功,如果程序执行到endTrans ...

  4. Android开发中的SQLite事务处理,即beginTransaction()方法

    使用SQLiteDatabase的beginTransaction()方法可以开启一个事务,程序执行到endTransaction() 方法时会检查事务的标志是否为成功,如果程序执行到endTrans ...

  5. Android 开发中 SQLite 数据库的使用

    SQLite 介绍 SQLite 一个非常流行的嵌入式数据库,它支持 SQL 语言,并且只利用很少的内存就有很好的性能.此外它还是开源的,任何人都可以使用它.许多开源项目((Mozilla, PHP, ...

  6. android开发中的5种存储数据方式

    数据存储在开发中是使用最频繁的,根据不同的情况选择不同的存储数据方式对于提高开发效率很有帮助.下面笔者在主要介绍Android平台中实现数据存储的5种方式. 1.使用SharedPreferences ...

  7. android开发之使用SQLite数据库存储

    http://blog.csdn.net/jason0539/article/details/16360835 SQLite 介绍 SQLite 一个非常流行的嵌入式数据库,它支持 SQL 语言,并且 ...

  8. 如何在Android开发中让你的代码更有效率

    最近看了Google IO 2012年的一个视频,名字叫做Doing More With Less: Being a Good Android Citizen,主要是讲如何用少少的几句代码来改善And ...

  9. Android开发系列之SQLite

    上篇博客提到过SQLite,它是嵌入式数据库,由于其轻巧但功能强大,被广泛的用于嵌入式设备当中.后来在智能手机.平板流行之后,它作为文件型数据库,几乎成为了智能设备单机数据库的必选,可以随着安卓app ...

随机推荐

  1. Signal in unit is connected to following multiple drivers VHDL

    参考链接 https://blog.csdn.net/jbb0523/article/details/6946899 出错原因 两个Process都对LDS_temp进行了赋值,万一在某个时刻,在两个 ...

  2. 【搬运】Wget 命令详解

    用过 Linux 系统的对于 wget 不陌生吧,从网上下载资源等操作都是少不了它,它体积小但功能集全,支持 FTP HTTP HTTPS 协议下载方式,支持断点续传 代理服务器. 现在 Window ...

  3. C# 绘制圆角矩形

    Graphics g = e.Graphics; // 圆角半径 ; // 要实现 圆角化的 矩形 Rectangle rect = , , panel4.Width - cRadius, panel ...

  4. win8外包公司——技术分享:参数传递

    页面之间传递参数 windows phone 的参数传递和web 差不多.用“?”号传递 多个参数的时候用 “&”做分隔. 我接着昨天的项目继续添加一个FourPage.xaml 在昨天的Th ...

  5. HBase过滤器的使用

    一.常用过滤器: 1.数据准备: Rowkey:001 Family:Quilfifier address value: 昆明市西山区 Rowkey:001 Family:Quilfifier age ...

  6. yii2常用路径获取

    public function actionGetUrlList() { echo "当前域名地址:".Yii::$app->request->hostInfo.&qu ...

  7. 『TensorFlow』读书笔记_Inception_V3_上

    1.网络背景 自2012年Alexnet提出以来,图像分类.目标检测等一系列领域都被卷积神经网络CNN统治着.接下来的时间里,人们不断设计新的深度学习网络模型来获得更好的训练效果.一般而言,许多网络结 ...

  8. selenium java 文件上传、下载

    1.webdriver对页面文件的下载 我们一般操作浏览器下载时会让我们选择下载的目录然后经过一系列操作后才进行文件下载操作,但是用webdriver不能按这样的方式操作.经过查询资料找到了如下的实现 ...

  9. 数据结构与算法之PHP排序算法(归并排序)

    一.基本思想 归并排序算法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,使每个子序列有序,再将已有序的子序列合并,得到完全有序的序列.该算法是采用分治法(Divid ...

  10. Lucene全文检索入门使用

    一. 什么是全文检索 全文检索是计算机程序通过扫描文章中的每一个词,对每一个词建立一个索引,指明该词在文章中出现的次数和位置.当用户查询时根据建立的索引查找,类似于通过字典的检索字表查字的过程 全文检 ...