I have many methods that in most cases follow the same algorithm, and ideally I want to be able to make calls to a common method that eliminates a lot of code duplication.
I have many methods like the ones below, I would optimally want to just be able to call Save<SQLiteLocation>(itemToSave);
, but I have a lot of problems, since the SQLiteConnection.Find<T>
methods will not accept abstract data types such as T in generics.
Is there any way around this, if I could fix it, I would save up to 150 lines of code
Here is my code:
public bool SaveLocation(ILocation location, ref int primaryKey) { var dbConn = new SQLiteConnection (dbPath); SQLiteLocation itemToSave = new SQLiteLocation (); itemToSave.LocationName = location.LocationName; itemToSave.Latitude = location.Latitude; itemToSave.Longitude = location.Longitude; itemToSave.PrimaryKey = location.PrimaryKey; ---------------------------------------------------------------------------------------- SQLiteLocation storedLocation = dbConn.Find<SQLiteLocation> (x => x.PrimaryKey == location.PrimaryKey); if (storedLocation != null) { dbConn.Update(itemToSave); return true; } else if (storedLocation == null) { dbConn.Insert(itemToSave); primaryKey = itemToSave.PrimaryKey; return true; } return false; }
And here another method shows how the code in both methods below my dashed line is basically the same
public bool SaveInvitation(IInvitation invitation, ref int primaryKey) { var dbConn = new SQLiteConnection(dbPath); SQLiteInvitation itemToSave = new SQLiteInvitation (); itemToSave.GroupName = invitation.GroupName; itemToSave.InviterName = invitation.InviterName; itemToSave.ParseID = invitation.ParseID; itemToSave.GroupParseID = invitation.GroupParseID; itemToSave.PrimaryKey = invitation.PrimaryKey; --------------------------------------------------------------------------------------- SQLiteInvitation storedInvitation = dbConn.Find<SQLiteInvitation> (x => x.PrimaryKey == invitation.PrimaryKey); if (storedInvitation != null) { dbConn.Update(itemToSave); return true; } else if (storedInvitation == null) { dbConn.Insert(itemToSave); primaryKey = itemToSave.PrimaryKey; return true; } return false; }
Guano source share