Saving collection of items to the sqlite table - xamarin.forms

When i had autoIncrement id in my sqlite table, i used this code to insert or update the item:
public string SaveItem(MyClass item)
{
if (item.id != null)
{
database.Update(item);
return item.id;
}
else
{
database.Insert(item);
return item.id;
}
}
Now id isn't AutoIncrement (i have my own unique id).
How can I check if the item exists or not in this case (item.id != null) ?
Thanks!

Check if item exists first:
public string SaveItem(MyClass item) {
if (item != null && item.id != null) {
database.Update(item);
return item.id;
} else {
// Do you still want to insert invalid items?
database.Insert(item);
return null;
}
}

Related

Problem with adding new object to data base

Hi i have an error when i trying add object to database. Error message is:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.
My adding methods:
public void AddProduct(string category, FormCollection formCollection, HttpPostedFileBase image) //Dodaje nowy produkt do bazy.
{
var product = GetNewProduct(category);
var EfContext = GetEfContext(category);
foreach(var property in product.GetType().GetProperties())
{
if(property.Name != "ImageData" && property.Name != "ImageMimeType")
{
var NewValue = Convert.ChangeType(formCollection[property.Name], property.PropertyType);
property.SetValue(product, NewValue);
}
else
{
if (property.Name == "ImageData")
{
property.SetValue(product, new byte[image.ContentLength]);
}
if(property.Name == "ImageMimeType")
{
property.SetValue(product, image.ContentType);
}
if(product.GetType().GetProperty("ImageData").GetValue(product) != null && product.GetType().GetProperty("ImageMimeType").GetValue(product) != null)
{
image.InputStream.Read((byte[])product.GetType().GetProperty("ImageData").GetValue(product), 0, image.ContentLength);
}
}
}
EfContext.GetType().GetMethod("AddProduct").Invoke(EfContext, new object[] { product });
}
And
public void AddProduct(GPU product)
{
product.Product_ID = productContext.items.Count() != 0 ? productContext.items.OrderByDescending(x => x.ProductID).Select(x => x.ProductID).FirstOrDefault() + 1 : 1;
context.GPUs.Add(product);
context.SaveChanges();
}

Attaching the DbEntityEntry to Context

i am trying to implement a log system to the entitiy framework context.
i want to get the deleted element primary key when its state is deleted.
this is my code:
if (item.State == EntityState.Added || item.State == EntityState.Deleted) {
log = new dt_islemLog();
log.eskiDeger = null;
log.islem = (item.State == EntityState.Added) ? Enums.GetDBValue(Enums.islemDurum.EKLENDI) : Enums.GetDBValue(Enums.islemDurum.SILINDI);
log.islemYapanKullanici_id = kullaniciID;
log.nesneAd = item.Entity.GetType().Name;
log.oturum_id = oturumID;
log.zaman = DateTime.Now;
base.SaveChanges();
var ID = GetPrimaryKeyValue(item);
log.nesneID = ID != null ? ID.ToString() : null;
this.dt_islemLog.Add(log);
}
And this is the method that i get the primary key
object GetPrimaryKeyValue(DbEntityEntry entry) {
try {
if (entry.State == EntityState.Detached)
((IObjectContextAdapter)this).ObjectContext.Attach((System.Data.Entity.Core.Objects.DataClasses.IEntityWithKey)entry.Entity);
var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
return objectStateEntry.EntityKey.EntityKeyValues[0].Value;
}
catch(Exception ex) {
return null;
}
}
But i can't attach the (entry.Entitiy) to context because the cast operation is invalid. How can i get the primary key ?
If someone needs i have found the solution. i have updated the primary key method to like this
object GetPrimaryKeyValue(DbEntityEntry entry)
{
try
{
if (entry.State == EntityState.Detached)
this.Set(entry.Entity.GetType()).Attach(entry.Entity);
var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
return objectStateEntry.EntityKey.EntityKeyValues[0].Value;
}
catch
{
return null;
}
}

"Not all code paths return a value" when returning View in MVC

I want to return a view if an object(country) is not null. But I get the error "Not All code paths return a value"
My code looks like this
public ActionResult Show(int id)
{
if (id != null)
{
var CountryId = new SqlParameter("#CountryId", id);
Country country = MyRepository.Get<Country>("Select * from country where CountryId=#CountryId", CountryId);
if (country != null)
{
return View(country);
}
}
}
This happens when you are returning something from within the "if" statement. The compiler thinks, what if the "if" condition is false? That way you are not returning anything even when you have the return type of "ActionResult" defined in the function. So add some default returns in the else statement:
public ActionResult Show(int id)
{
if (id != null)
{
var CountryId = new SqlParameter("#CountryId", id);
Country country = MyRepository.Get<Country>("Select * from country where CountryId=#CountryId", CountryId);
if (country != null)
{
return View(country);
}
else
{
return View(something);
}
}
else
{
return View(something);
}
}

What is the contents of the Request[] collection

When I access the Request object as a collection, where does it get it's data from?
For example I know
Request["someKey"]
will return the value of either
Request.QueryString["someKey"]
or
Request.Form["someKey"]
depending on which is set.
Are any other collections searched (cookies, session)?
What happens is the key value pair exists in several of the collections?
I took a look in MSDN, but couldn't find much info.
http://msdn.microsoft.com/en-us/library/system.web.httpcontext.request
Thanks for the help!
If you decompile this assembly and take a look at the source, it will look in QueryString, then Form, then Cookies, then ServerVariables, before finally returning null if none of them contain the item.
public string this[string key]
{
get
{
string item = this.QueryString[key];
if (item == null)
{
item = this.Form[key];
if (item == null)
{
HttpCookie httpCookie = this.Cookies[key];
if (httpCookie == null)
{
item = this.ServerVariables[key];
if (item == null)
{
return null;
}
else
{
return item;
}
}
else
{
return httpCookie.Value;
}
}
else
{
return item;
}
}
else
{
return item;
}
}
}

How to create auto generate id for ListOf rows returned

I am accessing list of data as shown below.
var result = (from Pages in PagesList.Items.OfType<SPListItem>()
select new ListImages
{
desc = Convert.ToString(Pages["Description"])
}).ToList();
What I want is to auto generate customized increamental id for the no of rows generated.
ex, slide-img-1, slide-img-2 etc.
public class ListImages
{
string _desc;
string _id;
public string id
{
get
{
if (_id != null)
return _id;
else
return string.Empty;
}
set { _id = value; }
}
public string desc
{
get
{
if (_desc != null)
return _desc;
else
return string.Empty;
}
set { _desc = value; }
}
}
Thanks,
Ashish
I don't know if it can be achieved with the Linq specific syntax, but writing your query like this, you could use the .Select() method that provides an index:
var result = PagesList.Items.OfType<SPListItem>()
.Select((page, index) => new ListImages
{
desc = Convert.ToString(page["Description"]),
id = String.Concat("slide-img-", index + 1)
})
.ToList();

Resources