I have an SQlite table with 4 Columns in Xamarin app.
I've already inserted 3 columns and now i need an update statement to Update 4th column with some values using for loop.
(OR)
Please suggest any better/other method to do the same.
Do you want to update the record in the sqlite DB?
If so you can use this model to update the record in the DB.prijem.BCode is PrimaryKey, we set the type of PrimaryKey is int and AutoIncrement, So, if the model's PrimaryKey is not equal zero, this record stored in the DB, we can update this record by the Model.
readonly SQLiteAsyncConnection _database;
public PrijemDatabase(string dbPath)
{
_database = new SQLiteAsyncConnection(dbPath);
_database.CreateTableAsync<Prijem>().Wait();
}
public Task<int> SavePrijemAsync(Prijem prijem)
{
if (prijem.BCode != 0)
{
return _database.UpdateAsync(prijem);
}
else
{
return _database.InsertAsync(prijem);
}
}
Here is my model.
public class Prijem
{
[PrimaryKey, AutoIncrement, Unique]
public int BCode { get; set; }
public string Name { get; set; }
public string FirmName { get; set; }
public string ItemCode { get; set; }
public string Count { get; set; }
}
Here is link about how to execute CRUD, you can refer to it.
https://learn.microsoft.com/en-us/xamarin/get-started/quickstarts/database?pivots=windows
Here is a demo about it.
https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/getstarted-notes-database/
Related
I am struggling to get an Item by ID using the asynchronous API of SQLite.Net Async PCL. Here is my model class
public class Invoice : IEntityBase
{
public Invoice()
{
LineItems = new List<LineItem>();
DateCreated = DateTime.Now;
}
[PrimaryKey, AutoIncrement, Column("_id")]
public int Id { get; set; }
public DateTime DateCreated { get; set; }
public int Term { get; set; }
public bool Paid { get; set; }
public decimal Total { get; set; }
public string Notes { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<LineItem> LineItems { get; set; }
}
And the LineItems that has a One to Many relationship here
[PrimaryKey, AutoIncrement, Column("_id")]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public int Qty { get; set; }
[ForeignKey(typeof(Invoice))]
public int InvoiceId { get; set; }
[ManyToOne]
public Invoice Invoice { get; set; }
Here is the constructor:
public SQLiteAsyncConnection DbConnection;
public InvoiceDatabase(ISQLitePlatform platform, string databasePath)
{
if (DbConnection == null)
{
var connectionAsync = new Func<SQLiteConnectionWithLock>(() =>
new SQLiteConnectionWithLock
(
platform,
new SQLiteConnectionString(databasePath, false)
)
);
DbConnection = new SQLiteAsyncConnection(connectionAsync);
DbConnection.CreateTableAsync<Invoice>();
DbConnection.CreateTableAsync<LineItem>();
}
}
Other CRUD methods (Insert, GetALL) is working except getting an Invoice by ID, and both Visual Studio and Xamarin Studio are not giving me any useful stacktrace.
Here is the Get Method
private readonly InvoiceDatabase _database;
public InvoiceRepository(ISQLitePlatform platform, string databasePath)
{
if (_database == null)
{
_database = new InvoiceDatabase(platform, databasePath);
}
}
public async Task<Invoice> GetInvoice(int id)
{
var result = await _database.DbConnection.Table<Invoice>()
.Where(t => t.Id == id)
.FirstOrDefaultAsync();
return result;
}
I am passing in the Android implementation of SQLite, and like I said the Database is created but I am unable to get the Invoice object back, I even tried
public Task<Invoice> GetInvoiceWithChildren(int id)
{
return _database.DbConnection.GetWithChildrenAsync<Invoice>(id);
}
Any Help will be greatly appreciated.
After three days of chasing shadows it turned out that it is just a very simple thing that is tripping me up. I am tying to save a List of objects like so
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<LineItem> LineItems { get; set; }
I missed the part of the documentation that repeats the fact that SQLite.Net is a lightweight ORM - that point could not be stressed enough so you will have to remove your full size ORM hats such EF. So after reading from the SQLite-Net Extension documentation which says
Text blobbed properties
Text-blobbed properties are serialized into a text property when saved and deserialized when loaded. This allows storing simple objects in the same table in a single column.
Text-blobbed properties have a small overhead of serializing and deserializing the objects and some limitations, but are the best way to store simple objects like List or Dictionary of basic types or simple relationships.
I change my proptery like so and everything is now working as expected. Off now to dealing with the nuances of Async and Await
[TextBlob("LineItemBlobbed")]
public List<LineItem> LineItems { get; set; }
public string LineItemBlobbed { get; set; }
I'm getting the following error when I try to insert a new row in one of my relational tables. I have the following two models:
public class CompanyCredit
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int creditId { get; set; }
public int planCredit { get; set; }
public DateTime? PlanCreditExpirationDate { get; set; }
}
And
public class CompanyInformation
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[Required]
[DisplayName("Company Name:")]
public string companyName { get; set; }
public string timeZone { get; set; }
//navigation Properties
public virtual CompanyCredit Credits { get; set; }
}
And this Relation in the dbContext
modelBuilder.Entity<CompanyInformation>().HasOptional(e => e.Credits);
I'm trying to add a record inside CompanyCredit table like so:
if (_company.Credits == null)
{
var _credits = new CompanyCredit();
_credits.planCredit = 200;
_credits.PlanCreditExpirationDate = System.DateTime.UtcNow.AddMonths(1);
_company.Credits = _credits;
repo.InsertOrUpdate(_company, User.Identity.Name);
}
And Finally Insert or update just marks Company as changed and _credit as added like so:
_db.Entry(_credits).State = System.Data.EntityState.Added;
_db.Entry(Company).State = System.Data.EntityState.Modified;
_db.SaveChanges();
When this runs I get the following Error that I just can't seem to find the reason to.
Cannot insert the value NULL into column 'creditId', table 'Project.dbo.CompanyCredits'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Thank in advanced for your help.
I found the problem was in the attribute [DatabaseGenerated(DatabaseGeneratedOption.Identity)] this should have been [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
I thought I would post this so others might benefit from it.
Could you please try reversing the order of entity state modification, just before the saveChanges call
_db.Entry(Company).State = System.Data.EntityState.Modified;
_db.Entry(_credits).State = System.Data.EntityState.Added;
_db.SaveChanges();
This is my code:
public void DeleteFolder(Entities.DocumentFolder folder)
{
DeleteFilesFromServer(folder.Id);
_dbContext.Entry(folder).State = EntityState.Deleted;
_dbContext.SaveChanges();
}
public void DeleteFilesFromServer(int id)
{
var allDocuments = _dbContext.Document.Where(x => x.FolderId == id).ToList();
foreach (var filePath in allDocuments.Select(document => HttpContext.Current.Server.MapPath("~/Documents/") + document.DocumentFileName).Where(System.IO.File.Exists))
{
System.IO.File.Delete(filePath);
}
}
public class DocumentFolder
{
public DocumentFolder()
{
Documents=new List<Document>();
}
public int Id { get; set; }
public string FolderName { get; set; }
public int ParentFolderId { get; set; }
public List<Document> Documents { get; set; }
}
public class Document
{
public int Id { get; set; }
public string DocumentName { get; set; }
public string DocumentFileName { get; set; }
public int FolderId { get; set; }
public virtual DocumentFolder Folder { get; set; }
}
By executing the delete operation I got the following exception:
System.InvalidOperationException: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
If I remove the DeleteFilesFromServer(int id) method the deletion working. Can someone help me?
If you want to delete the DocumentFolder, you need to delete the Document objects related to the DocumentFolder because in your model the field Folder is not nullable. This happens only if the dbContext knows that the the Document objects exist, i.e. if you load the documents with the Select method.
I'm using the mongo-csharp-driver to query my Mongo entities.
I have the following objects which are stored in the Mongo:
public class Table
{
public int Id { get; private set; }
public string Description{ get; private set; }
public List<Player> Players { get; private set; }
public Table()
{
}
}
public class Player
{
public int Id { get; private set; }
public string Username{ get; private set; }
public Player()
{
}
}
When I'm trying to query the "Table" object by id or description, I get the appropriate results, but when I try to query by the list of player, I get null:
// Works ok
var tab1 = mongo.GetCollection<Table>().Where(g => g.Description == "Test");
// Always return null, although should return the same result
var tab2 = mongo.GetCollection<Table>().Where(g => g.Players.Count > 90).FirstOrDefault();
What am I missing here?
Thanks,
Nir.
The issue is that Count property is translated into the $size query operator.
From the linked Advanced Queries page you can see that:
"You cannot use $size to find a range of sizes (for example: arrays
with more than 1 element)."
I have an entity defined as in a db First Model:
public class Merlin_BR_Condiciones_Item
{
public int IntIdGrupoCondiciones { get; set; }
public string StrCondicion { get; set; }
[Key]
public int IntIdCondicion { get; set; }
public virtual Merlin_BR_Condiciones_Item_Grupos Merlin_BR_Condiciones_Item_Grupos { get; set; }
}
And A controller generated automatically that has this create action:
public ActionResult Create(int pIntIdGrupoCondiciones = 0 )
{
ViewBag.IntIdGrupoCondiciones = new SelectList(db.Merlin_BR_Condiciones_Item_Grupos, "IntIdGrupoCondiciones", "StrDescripcionGrupo");
return View();
}
[HttpPost]
public ActionResult Create(Merlin_BR_Condiciones_Item merlin_br_condiciones_item)
{
if (ModelState.IsValid)
{
//================================================================================
// This section add the current key to IntIdCondicion
//================================================================================
var max = from c in db.Merlin_BR_Condiciones_Item
select c;
merlin_br_condiciones_item.IntIdCondicion = max.AsQueryable().Max(x => x.IntIdCondicion) + 1;
//================================================================================
db.Merlin_BR_Condiciones_Item.Add(merlin_br_condiciones_item);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.IntIdGrupoCondiciones = new SelectList(db.Merlin_BR_Condiciones_Item_Grupos, "IntIdGrupoCondiciones", "StrDescripcionGrupo", merlin_br_condiciones_item.IntIdGrupoCondiciones);
return View(merlin_br_condiciones_item);
}
This Entity has an Id Column assigned manually in the HttPost (create action).
The problem is that an error was idicating me that Can't insert NULL Value in IntIdCondicion column.
Following step by step the code the value allways return a valid key.
Tks for your help.
By default EF expects that all integer primary keys are generated in a database. So modify your mapping and tell EF that your primary key is not autogenerated:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int IntIdCondicion { get; set; }
If you are using EDMX you must configure StoreGeneratedPattern to None in IntIdCondicion properties.