简体   繁体   中英

How to implement Insert, Update and Delete in a parent class that works for all database models using sqlite-net?

I'm using a SQLite database in a Windows 8 Store Application . Furthermore I use the SQLite wrapper sqlite-net to do operations on the database.

I will explain this in detail so that you understand my situation. There are Model classes that contain the business logic, for example the class Location . Then there are DatabaseModels from which the Database Tables are generated, for example LocationDb .

I don't want to implement the basic database methods like Insert(Model model), Update(Model model) , Delete(int id) , GetAllRecords() and GetRecord(int id) in every Model class. Instead I want to implement these methods in a base class of all models. This base class of all models is called ModelBase ; the base class of all database Models is DbModelBase .

There is no problem implementing the Insert method as follows for all models:

    public int Insert(ModelBase model)
    {
        int id;
        using (var db = new SQLite.SQLiteConnection(MainApplication.DBPath))
        {
            db.Insert(model.GetDbModelFromModel());
            id = (int)SQLite3.LastInsertRowid(db.Handle);
        }
        return id;
    }

But I don't know how to implement the other ones using sqlite-net. I need to find a specific data record in a specific table. I have a model object which contains the id. But how to make one method work with all model classes without explicitly calling the specific table? The following code works for a single specific database table...

        using (var db = new SQLite.SQLiteConnection(MainApplication.DBPath))
        {
            var queryResult = db.Table<LocationDb>().Where(l => l.Id == model.Id);
            if (queryResult.Count() == 1)
            {
                db.Update(new TeacherDb(model));
            }
        }

... but I can not write

var queryResult = db.Table<typeof(databaseModel)>().Where(t => t.Id == model.Id);

为此编写通用函数

What about this solution:

public class BaseModel<T> where T : Type
{
    protected T Id;
    /// <summary>
    /// Adds a new record to data base. It doesn't check for record existance.
    /// </summary>
    /// <returns></returns>
    protected BaseModel<T> Add() 
    {
        try
        {
            var entities = Variable.CurrentEntities;
            var dbSet = entities.Set<BaseModel<T>>();
            var result = dbSet.Add(this);
            entities.SaveChanges();
            return result;
        }
        catch (Exception exception)
        {
            LogException.HandleException(exception);
            return null;
        }
    }

    protected bool Update()
    {
        try
        {
            var entities = Variable.CurrentEntities;
            var dbSet = entities.Set<BaseModel<T>>();
            var original = dbSet.Find(this);
            entities.Entry(original).CurrentValues.SetValues(this);
            entities.SaveChanges();
            return true;
        }
        catch (Exception exception)
        {
            LogException.HandleException(exception);
            return false;
        }
    }

    protected BaseModel<T> Delete()
    {
        try
        {
            var entities = Variable.CurrentEntities;
            var dbSet = entities.Set<BaseModel<T>>();
            var result = dbSet.Remove(this);
            entities.SaveChanges();
            return result;
        }
        catch (Exception exception)
        {
            LogException.HandleException(exception);
            return null;
        }
    }

    protected bool Upsert()
    {
        try
        {
            var entities = Variable.CurrentEntities;
            var dbSet = entities.Set<BaseModel<T>>();
            dbSet.AddOrUpdate(this);
            return true;
        }
        catch (Exception exception)
        {
            LogException.HandleException(exception);
            return false;
        }
    }

    protected BaseModel<T> Save()
    {
        try
        {
            var entities = Variable.CurrentEntities;
            var dbSet = entities.Set<BaseModel<T>>();
            var original = dbSet.Find(Id);
            if (original == null)
            {
                original = dbSet.Add(this);
            }
            else
            {
                entities.Entry(original).CurrentValues.SetValues(this);
            }
            entities.SaveChanges();
            return original;
        }
        catch (Exception exception)
        {
            LogException.HandleException(exception);
            return null;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM