Xamarin项目中SQLite-Net的通用存储库 [英] Generic Repository for SQLite-Net in Xamarin Project

查看:94
本文介绍了Xamarin项目中SQLite-Net的通用存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法为Xamarin项目编写通用存储库,而不是为对象中的每个实体编写不同的存储库。 Xamarin Tasky Pro 示例具有一个用于任务实体,因为它是它唯一的实体。

I am wondering if there is a way to write a generic repository for my Xamarin project versus writing a different Repository for each entity in my object. The Xamarin Tasky Pro example have one Repository for the Task entity because that is the only entity it has.

在我自己的项目中,我有多个实体,所以我的问题是如何使
成为实体。跟随客户资料库变得通用,以便ProductManager,EmployeeManager等可以使用它。如果您知道示例或博客文章,请为我指明正确的方向

In my own project I have more than one Entity, so my question is how can I make the following Customer Repository to become generic so that the ProductManager, EmployeeManager, etc can use it. If you know of an example or a blog post please point me to the right direction

namespace App.DataLayer
{
    public class CustomerRepository
    {
        private ProntoDatabase _db = null;
        protected static string DbLocation;
        protected static CustomerRepository Me;

        static CustomerRepository()
        {
            Me = new CustomerRepository();
        }

        protected CustomerRepository()
        {
            //set the db location;
            DbLocation = DatabaseFilePath;

            //instantiate the database
            _db = new ProntoDatabase(DbLocation);
        }


        public static string DatabaseFilePath
        {
            get
            {
                const string sqliteFilename = "CustomerDB.db3";
                var libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                var path = Path.Combine(libraryPath, sqliteFilename);
                return path;
            }
        }


        // CRUD (Create, Read, Update and Delete) methods

        public static Customer GetCustomer(int id)
        {
            return Me._db.GetItem<Customer>(id);
        }

        public static IEnumerable<Customer> GetCustomers()
        {
            return Me._db.GetItems<Customer>();
        }

        public static int SaveCustomer(Customer item)
        {
            return Me._db.SaveItem(item);
        }

        public static int DeleteCustomer(int id)
        {
            return Me._db.DeleteItem<Customer>(id);
        }
    }


推荐答案

此是一个老问题,但这是我的实现。

This is an old question but here is my implementation.

我在使用异步连接,因为它们在移动项目中提供了更好的性能。我安装的块是Core项目上的 Sqlite.Net-PCL / SQLite.Net.Async-PCL

I´m using async connections as they provide better performance in mobile projects. The nuggets I installed are Sqlite.Net-PCL/SQLite.Net.Async-PCL on the Core project and the corresponding nuget on the Android project.

我的存储库如下:

using System;
using System.Collections.Generic;
using Core.Models;
using SQLite.Net;
using System.Linq;
using SQLite.Net.Async;
using System.Threading.Tasks;
using System.Linq.Expressions;

namespace Core.Managers
{
    public interface IRepository<T> where T : class, new()
    {
        Task<List<T>> Get();
        Task<T> Get(int id);
        Task<List<T>> Get<TValue>(Expression<Func<T, bool>> predicate = null, Expression<Func<T, TValue>> orderBy = null);
        Task<T> Get(Expression<Func<T, bool>> predicate);
        AsyncTableQuery<T> AsQueryable();
        Task<int> Insert(T entity);
        Task<int> Update(T entity);
        Task<int> Delete(T entity);
    }

    public class Repository<T> : IRepository<T> where T : class, new()
    {
        private SQLiteAsyncConnection db;

        public Repository(SQLiteAsyncConnection db)
        {
            this.db = db;
        }

        public AsyncTableQuery<T> AsQueryable() => 
            db.Table<T>();

        public async Task<List<T>> Get() => 
            await db.Table<T>().ToListAsync();

        public async Task<List<T>> Get<TValue>(Expression<Func<T, bool>> predicate = null, Expression<Func<T, TValue>> orderBy = null)
        {
            var query = db.Table<T>();

            if (predicate != null)
                query = query.Where(predicate);

            if (orderBy != null)
                query = query.OrderBy<TValue>(orderBy);

            return await query.ToListAsync();
        }

        public async Task<T> Get(int id) => 
             await db.FindAsync<T>(id);

        public async Task<T> Get(Expression<Func<T, bool>> predicate) =>
            await db.FindAsync<T>(predicate);

        public async Task<int> Insert(T entity) => 
             await db.InsertAsync(entity);

        public async Task<int> Update(T entity) =>
             await db.UpdateAsync(entity);

        public async Task<int> Delete(T entity) =>
             await db.DeleteAsync(entity);
    }
}

一些使用示例:

var connection = new SQLiteAsyncConnection(() => sqlite.GetConnectionWithLock());
await connection.CreateTablesAsync<Ingredient, Stock>();

IRepository<Stock> stockRepo = new Repository<Stock>(connection);
IRepository<Ingredient> ingredientRepo = new Repository<Ingredient>(connection);

var stock1 = new Stock { 
    IngredientId = 1,
    DaysToExpire = 3,
    EntryDate = DateTime.Now,
    Location = StockLocations.Fridge,
    MeasureUnit = MeasureUnits.Liter,
    Price = 5.50m,
    ProductName = "Leche Auchan",
    Quantity = 3,
    Picture = "test.jpg",
    Family = IngredientFamilies.Dairy
};

var stockId = await stockRepo.Insert(stock1);

var all = await stockRepo.Get();
var single = await stockRepo.Get(72);
var search = await stockRepo.Get(x => x.ProductName.StartsWith("something"));
var orderedSearch = await stockRepo.Get(predicate: x => x.DaysToExpire < 4, orderBy: x => x.EntryDate);

如果存储库不满足您的查询需求,则可以使用AsQueryable():

If the Repository does not meet your query needs, you can use AsQueryable():

public async Task<List<Stock>> Search(string searchQuery, StockLocations location, IngredientFamilies family)
{
    var query = stockRepo.AsQueryable();

    if (!string.IsNullOrEmpty(searchQuery))
    {
        query = query.Where(x => x.ProductName.Contains(searchQuery) || x.Barcode.StartsWith(searchQuery));
    }
    if (location != StockLocations.All)
    {
        query = query.Where(x => x.Location == location);
    }
    if (family != IngredientFamilies.All)
    {
        query = query.Where(x => x.Family == family);
    }

    return await query.OrderBy(x => x.ExpirationDays).ToListAsync();
}

这篇关于Xamarin项目中SQLite-Net的通用存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆