sqlite in Xamarin.Froms how to Update individual record in Local DB - sqlite

I am trying to update individual records in sqlite database. I know how to Insert and delete records. I'd like to Update an individual record in a similar way to how I am deleting an individual record below. This uses a linq statement to get the record by Asset ID. I'd then like to pass my data to this to update.
I've also included how I insert a new record for reference. Does anybody have an example that they could share?
Delete an existing record
using (SQLiteConnection localconn = new SQLiteConnection(App.FilePath))
{
localconn.CreateTable<Road_Inspections>();
localconn.Table<Road_Inspections>().Where(x => x.Unique_ID == unique_ID).Delete();
}
Insert new record
Road_Inspections lri = new Road_Inspections()
{
ID = id,
Road_ID = Road_ID.Text.ToString(),
Asset_ID = Asset_ID.Text.ToString(),
Defect_Type = txtDefectType.Text.ToString(),
Response = txtResponse.Text.ToString(),
Inspection_Date = DateTime.Now,
};
using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
{
conn.CreateTable<Road_Inspections>();
int rowsAdded = conn.Insert(lri);
await DisplayAlert("Success", "Inspeciton Saved to Device", "OK");
}

You need a primary Key or Id in your object Announcement to identify your unique object in your database, for example:
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
Since you want to update you have to get the original entry from the database first.
And then you can edit and update it. So, you don't need to delete it before you insert a new one.
In xamarin form you can use nuget sqlite-net-pcl to achieve this.
Please refer to the following code:
public Task<int> SaveItemAsync(TodoItem item)
{
if (item.ID != 0)
{
return Database.UpdateAsync(item);
}
else
{
return Database.InsertAsync(item);
}
}
For more details,you can check: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/databases .
And there is a sample included in above document, you can check it here:https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/todo/

Related

Dapper question. Getting values from returned object

Just started learning Dapper. I have an ADO.NET background. Using a demo I downloaded, I can insert/delete data from a webform into a MySql table just fine. This, however, I have searched all morning on.
In retrieving a single row from the db by ID, it doesn't return a LIST<>, it seems to be just an object (using code from the demo I downloaded). The query works, I get the object back. It has the fields: "ProductID, Description and Price".
The only way I could get the values to those three fields was like this:
System.Reflection.PropertyInfo pi = Product.GetType().GetProperty("ProductID");
System.Reflection.PropertyInfo desc = Product.GetType().GetProperty("Description");
System.Reflection.PropertyInfo price = Product.GetType().GetProperty("Price");
int _ProductID = (int)(pi.GetValue(Product, null));
string _Description = (string)(desc.GetValue(Product, null));
decimal _Price = (decimal)(price.GetValue(Product, null));
This works and gets the correct values for the three fields.
I'm used to looping through DataTables, but I just think there is probably a better way to get those values.
Is this the correct way to do this or am I missing something? I did actually read documentation and mess with this all morning before asking, too.
Some of the things I looked at seem to be very complex. I thought Dapper was supposed to simplify things.
OK, Thanks Marc. It was difficult for me to see what was supposed to be in the Dapper class files and what was supposed to be in my code behind. The original demo way of getting a product by ID had the query as .FirstOrDefault();
I changed everything to return a List<> and it all worked. I'm sure my ADO.NET is showing, but this works. In Dapper class files:
public List<Product> ProductAsList(int Id)
{
return this._db.Query<Product>("SELECT * FROM Cart_product WHERE ProductID=#Id", new { Id = Id }).**ToList()**;
}
This is just getting one row that matched the ProductID.
In page codebehind:
protected void CartItemAdd(string ProductId) // passing it the selected ProductID
{
var results = cartservice.ProductAsList(Convert.ToInt32(ProductId));
// returns that one row using Dapper ProductAsList(ProductId)
int _ProductId = 0;
string Description = string.Empty;
decimal Price = 0;
// Loop through the list and get the value of each item:
foreach (Product obj in results)
{
_ProductId = obj.ProductID;
Description = obj.Description;
Price = obj.Price;
}
// Using Dapper to insert the selected product into the shopping cart (table):
String UserName = "jbanks";
cartitem = new CartItem();
cartitem.ProductID = _ProductId;
cartitem.Quantity = 1;
cartitem.Description = Description;
cartitem.Price = Price;
cartitem.Created = DateTime.Now;
cartitem.CreatedBy = UserName;
result = cartservice.AddCartItem(cartitem);
if (result)
{
lblMessage.Text = string.Empty;
lblMessage.Text = "Successfully added a cart item";
}
}
}
It does indeed look up the product from one table and insert a selected item into another table.
Thanks again!
The main Query<T> API returns an IEnumerable<T>, which often will be a List<T>; the AsList<T>() extension method can get it back to a list without a copy, but either way: they are just T, for whatever T you asked for. If you asked for Query<Product>, then: they should be Product instances:
var results = connection.Query<Product>(someSql, someArgs); // perhaps .AsList()
foreach (Product obj in results) { // "var obj" would be fine here too
// now just use obj.ProductID, obj.Description and obj.Price
}
If that didn't work: check that you used the <T> version of Query. There is a non-generic variant too, which returns dynamic. Frankly, you should almost always use the <T> version.
Note: I'm assuming that somewhere you have something like
class Product {
public int ProductID {get;set;}
public string Description {get;set;}
public decimal Price {get;set;}
}

Table contains only two foreign keys. But its not showing in EDMX model using database first approach Entity Framework

These are my model classes
I have three tables
But when I update my model, the PurchaseReturnDetail table is not there in the model, and it creates a one-to-many relationship between PurchaseReturn and PurchaseDetail.
I'm using repository pattern and I don't know how to insert transactions in PurchaseReturnDetail table.
Following is my code to insert transaction. but it gives exception
Message = "An entity object cannot be referenced by multiple instances of IEntityChangeTracker."
public async Task<Response> SaveAsync(PurchaseReturn purchaseReturn, List<string> serialNoList)
{
PurchaseReturnRepository rep = new PurchaseReturnRepository();
decimal totalRate = 0;
foreach (var serialNo in serialNoList)
{
var purchaseDetail = await PurchaseService.Instance.GetSinglePurchasedItemDetailAsync(serialNo);
purchaseReturn.PurchaseDetails.Add(purchaseDetail);
//Calculating total rate to update supplier balance
totalRate += purchaseDetail.Rate;
}
var response = await rep.AddAsync(purchaseReturn);
if (response.Success)
{
//Updating Supplier Balance
response = await SupplierService.Instance.UpdataBalanceAsync(purchaseReturn.SupplierId, totalRate, false);
response.Msg = "Items has beed returned and stock is updated";
}
return response;
}
NOTE : I'm using database first approach

How to handle multiple session variables in ASP .Net?

As a part of online shopping, I implemented a cart using Session.
I have implemented the Cart in the following manner :
Session[pname] = qty;
where pname is a string variable which holds the name of the product and I used that as the key. qty is an integer variable which holds the number of items of that particular product.
To display the cart items I simply used the following loop :
foreach(string keys in Session.Keys)
Through this I get the names of the products along with the associated quantity and using this I display the cart items. The problem arises when I also have a session for the user active on the same page.
Session["uname"] = user_name;
And while retrieving the keys using Session.Keys, the uname gets included which I don't want as I need only the product's names. Is there any way I can read the keys from Session[pname] without reading from Session["uname"]?
Instead of storing an object in session for each product and quantity, just store a single object (e.g. List) which contains all of your cart items.
Here is an example which you could tweak to meet your needs:
First, a simple object to store the data:
public class CartItem {
public string Name { get; set; }
public int Quantity { get; set; }
}
Then if you need to add an object to the cart list:
var cartItems = new List<CartItem>();
cartItems.Add(new CartItem() {
Name = "",
Quantity = 1
});
Session["Cart"] = cartItems;
//Need to fetch the cart items later on?
cartItems = (List<CartItem>)Session["Cart"];
Obviously this can be implemented differently and this was just a quick example.
You mentioned needing an easier fix than what Justin Helgerson said, so here's a couple of suggestions, but they feel a little quick and dirty. Justin's is probably the superior solution. I used a quick Console app to demonstrate this, so place your constants where they belong, and you obviously don't have to create a dictionary.
const string USERSESSION = "uname";
Dictionary<string, object> session = new Dictionary<string, object>();
session["item1"] = 2;
session["item2"] = 1;
session[USERSESSION] = "StackOverflowUser";
// print cart items - minus the user name session key
foreach (string key in session.Keys.Where(s => s != USERSESSION))
{
Console.WriteLine("Key: {0} Value: {1}", key, session[key]);
}
Alternatively, if you plan on there being more keys than just "uname", use the Linq Except method.
// build up except set
List<string> exceptKeys = new List<string>
{
USERSESSION
};
foreach (string key in session.Keys.Except(exceptKeys))
{
Console.WriteLine("Key: {0} Value: {1}", key, session[key]);
}

dynamo db query

I have my dynamo db table as follows:
HashKey(xyz) ,RangeKey(timestamp)
Now for each hash key i have set of range key.
Now i want to query based on set of hashkey and i want only most recent value correspoding to that to be fetched .I dont want to do in memory sorting and then picking most recent version.
Can i do this in any way?
Use case is that i will do a bulkget and pass set of hashkey (say 100) , so i want to get one record for each hashkey
You (currently) can't set constraints on a batch get. See http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API_BatchGetItems.html
However, for single hash keys, you can set the direction using ScanIndexForward. See http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API_Query.html for information.
Sample java code:
new QueryRequest().withTableName("table-name")
.withScanIndexForward(false)
.withLimit(1)
.withHashKeyValue(new AttributeValue().withS("hash-key"));
It will not be very efficient though, as you will need to make this call 100 times.
Use ScanIndexForward(true for ascending and false for descending) and can also limit the result using setLimit value of Query Expression.
Please find below the code where used QueryPage for finding the single record.
public EventLogEntitySave fetchLatestEvents(String id) {
EventLogEntitySave entity = new EventLogEntitySave();
entity.setId(id);
DynamoDBQueryExpression<EventLogEntitySave> queryExpression = new DynamoDBQueryExpression<EventLogEntitySave>().withHashKeyValues(entity);
queryExpression.setScanIndexForward(false);
queryExpression.withLimit(1);
queryExpression.setLimit(1);
List<EventLogEntitySave> result = dynamoDBMapper.queryPage(EventLogEntitySave.class, queryExpression).getResults();
System.out.println("size of records = "+result.size() );
result.get(0);
}
#DynamoDBTable(tableName = "PROD_EA_Test")
public class EventLogEntitySave {
#DynamoDBHashKey
private String id;
private String reconciliationProcessId;
private String vin;
private String source;
}
public class DynamoDBConfig {
#Bean
public AmazonDynamoDB amazonDynamoDB() {
String accesskey = "";
String secretkey = "";
//
// creating dynamo client
BasicAWSCredentials credentials = new BasicAWSCredentials(accesskey, secretkey);
AmazonDynamoDB dynamo = new AmazonDynamoDBClient(credentials);
dynamo.setRegion(Region.getRegion(Regions.US_WEST_2));
return dynamo;
}

"Cannot add an entity that already exists" while deleting and recreating record with LINQ

While trying to delete a record in a database and recreate it afterwards, using LINQ, I get the error: Cannot add an entity that already exists.
Although the record is deleted.
I am initialising my Sales_header object with data I get from a LINQ query in method
SelectOrdersByOrderID(OrderID).
If the OrderID of the Salesheader meets a certain condition, I want to delete the record in the database (Delete(Sales_header SalesHeader)), add additional values to the object and insert a new record in the database (Insert(Sales_header SalesHeader)).
I do not want to update the record, but delete it and recreate it.
Sales_header SalesHeader = new Sales_header();
SalesHeader = SalesHeaderClass.SelectOrdersByOrderID(OrderID) as Sales_header;
if (SalesHeader.OrderID == *certain value*)
{
SalesHeaderClass.Delete(SalesHeader);
SalesHeader.Orderdate = DateTime.Today;
SalesHeader.Ordertime = DateTime.Now;
SalesHeaderClass.Insert(SalesHeader);
}
...
Method in SalesHeaderClass to select the SalesHeader via LINQ
public static object SelectOrdersByOrderID(int OrderID)
{
var Query = (from p in dc.Sales_headers
where p.OrderID.Equals(OrderID)
select p).SingleOrDefault();
return Query;
Method in SalesHeaderClass to insert the SalesHeader via LINQ
public static void Insert(Sales_header SalesHeader)
{
dc.Sales_headers.InsertOnSubmit(SalesHeader);
dc.SubmitChanges();
}
Method in SalesHeaderClass to delete the SalesHeader via LINQ
public static void Delete(Sales_header SalesHeader)
{
var DelOrder = (from p in dc.Sales_headers
where p.OrderID == SalesHeader.OrderID
select p).Single();
dc.Sales_headers.DeleteOnSubmit(DelOrder);
dc.SubmitChanges();
}
What do I have to do to be able to insert the record?
Creating a new object with the same values does not help.
Aside from the question why an update is not suitable.
You need two contexts to first delete the record, and then insert the record. EF keeps all inserts/updates/deletes in memory until you do a SubmitChanges(), so you cannot have two entities with the same ID.
But to execute the whole things as a single transaction, you're going to need a TransactionScope.
using (var scope = new TransactionScope()) {
using (var salesHeader SalesHeader = new Sales_header()) {
// Delete record
...
salesHeader.SubmitChanges();
}
using (var salesHeader SalesHeader = new Sales_header()) {
// Insert record
...
salesHeader.SubmitChanges();
}
// Mark transaction complete
scope.Complete();
}
To fix this issue, use different datacontext for delete and insert operation.

Resources