I am working with Xamarin forms and I have implemented SQLite database using Sqlite-net-pcl nuget package. The problem is that the database is initially saving a row but is unable to update or delete any row. Here is the code in which I save and delete the database row with a Key.
public Task<int> SaveItemAsync(SQLiteRowData item)
{
if (item.ID != 0)
{
return database.UpdateAsync(item);
}
else
{
return database.InsertAsync(item);
}
}
public Task<int> DeleteItemAsync(SQLiteRowData item)
{
return database.DeleteAsync(item);
}
public Task<int> DeleteItemAsyncWithKey(string key)
{
Task<SQLite.SQLiteRowData> lSQLiteRowTaskData =
App.sqliteConnectionPath.GetItemForKeyAsync(key);
SQLite.SQLiteRowData lSQLiteRowData = lSQLiteRowTaskData.Result;
return database.DeleteAsync(lSQLiteRowData);
}
public async Task<bool> DeleteUserPreferencesAsync()
{
Boolean lReturnValue = false;
try
{
Task<SQLiteRowData> lSQLiteRowDataTask = App.sqliteConnectionPath.GetItemForKeyAsync("UserPreferences"); SQLiteRowData lSQLiteRowData = lSQLiteRowDataTask.Result;
if (lSQLiteRowData != null) {
await DeleteItemAsync(lSQLiteRowData);
lReturnValue = true;
}
}
catch (Exception ex)
{
EMAUtilities.printLogs(ex.Message);
}
return lReturnValue;
}
// Used for saving userpreference
SQLiteRowData lSQLiteRowData = new SQLiteRowData("UserPreferences", lValue);
Task<int> x = SaveItemAsync(lSQLiteRowData);
Can anyone point out the mistake I have done in this, Thanks in advance
Related
I'm trying to return the key of the match created / updated in VS2022 using Xamarin on Android.
The below code works perfectly, but returns the amount of rows updated / inserted.
public class GameDatabase
{
readonly SQLiteAsyncConnection database;
public void SaveGame()
{
Task<DBMatch> matchResult = SaveGameAsync(dbMatch);
_match.matchKey = matchResult.Result.matchKey;
}
public Task<int> SaveMatchAsync(DBMatch dbMatch)
{
if (dbMatch.matchKey != 0)
{
// Update an existing Game.
return database.UpdateAsync(dbMatch);
}
else
{
// Save a new Game.
return database.InsertAsync(dbMatch);
}
}
}
How do I update it to return the key? I seem to have gone round the houses about 20 times changing it to async and await as I believe the object is updated with the key, but then it just hangs on await.
e.g.
public async Task<DBMatch> SaveGameAsync(DBMatch dbMatch)
{
if (dbMatch.matchKey != 0)
{
// Update an existing Game.
await database.UpdateAsync(dbMatch);
}
else
{
// Save a new Game.
await database.InsertAsync(dbMatch);
}
return dbMatch;
}
It seems like the answer was to not use async or Tasks at all, and instead just use Wait().
DBMatch matchResult = SaveGameAsync(dbMatch);
_match.matchKey = matchResult.matchKey;
public DBMatch SaveGameAsync(DBMatch dbMatch)
{
if (dbMatch.matchKey != 0)
{
// Update an existing Game.
database.UpdateAsync(dbMatch).Wait();
}
else
{
// Save a new Game.
database.InsertAsync(dbMatch).Wait();
}
return dbMatch;
}
I would like to update data using C# and Entity Framework Core.
But the result of Swagger is different from the result of executing the API in axios.
The variable "todoList" is stored with data in Swagger and returned null in axios.
Why a value of "todoList" is null?
Please tell me about it.
Thank you!
This is a Code.
public bool updateCompFlg(string operatorId, string id)
{
// Call Update!
// "_repository is an Interface."
if (_repository.Update(operatorId, id))
{
return true;
}
else
{
return false;
}
}
This is the code that actually updates the data.
public bool Update(string operatorId, string id)
{
// ★The results here are different.
var todoList = _context.TODOLIST.Where(u => u.seqNo.Equals(id)).FirstOfDefault();
todoList.operatorId = operatorId;
todoList.resultFlg = "1";
_context.Update(todoList);
try
{
_context.SaveChange();
return true;
}
catch (SystemException ex)
{
throw ex;
}
}
This is my first question here so I'm really open for opinions, I searched a lot about ASP.NET Core MVC and still I don't have enough answers if I'm writing code in right way.
In many tutorials on Youtube I saw people create ASP.NET Core MVC applications with CRUD operations but there were just simple without any logic and all code was in controllers.
What if I want add some logic for example checking if my record already exists in the database? Where should I put this?
I have class Patient and I want add patient to database so I got in patient controller this :
public async Task<IActionResult> Create([Bind("PatientId,Name,Surname,Pesel")] Patient patient)
{
if (ModelState.IsValid)
{
String result = facade.Add_patient(patient);
if (result == "Patient added")
{
_context.Add(patient);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
else
{
ViewBag.Message = "Patient exists";
return View();
}
}
}
Facade is my class in model folder where I have this :
public class Facade
{
private Database_controller _context;
public Facade(Database_controller context)
{
_context = context;
}
private List<Patient> patients = new List<Patient>();
public List<Patient> Patients { get => patients; set => patients = value; }
public void updatedata()
{
patients = _context.Patients.ToList();
}
public string Add_patient(Patient patient)
{
Patient Patient = new Patient();
Patient.Name = patient.Name;
Patient.Surname = patient.Surname;
Patient.Pesel = patient.Pesel;
String if_is = addpacjent(Patient);
if (!"Is".Equals(if_is))
{
return "Patient added";
}
else
{
return "Patient exists";
}
}
public String addpacjent(Patient val)
{
bool if_is = patients.Contains(val);
if (if_is == true)
{
return ("Is");
}
else
{
patients.Add(val);
return null;
}
}
}
In Patient class is override method equals for checking
public override bool Equals(Object ob)
{
String Name = Surname;
String Name2 = ((Patient)ob).Surname;
String Pesel1 = Pesel;
String Pesel2 = ((Patient)ob).Pesel;
bool a = Name.Equals(Name2);
if (Pesel2 != "0")
{
bool b = Pesel1.Equals(Pesel2);
bool c = false;
if (a && b == true)
{
c = true;
}
return c;
}
else
return a;
}
Is it the right way? Should I have method _context.Add(patient) in Facade or controller? Where should I check existence in database?
I already have application which I want write in .NET Core in Winforms so I want use as many as possible code from Winforms classes so it's why I started coding like this in ASP.NET Core MVC
The easiest way is to use Any(),this is because Any() will return as soon as it finds a match.
Like my following:
public IActionResult Test()
{
//Simulation data:
var patient = new Patient
{
Name="AA",
SumName="AA-aa",
Pesel="23"
};
//Here you can add your conditions.
if (!_context.Patients.Any(o => o.Name == patient.Name&&o.SumName==patient.SumName&&o.Pesel==patient.Pesel))
{
_context.Add(patient);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
else
{
ViewBag.Message = "Patient exists";
return View();
};
}
Below is the demo data in my database:
Sample effect display:
I need to add a picture and store the picture Id and product Id in a seperate productPicture table. You can't add a picture without an existing product. How to achieve this?
This is my code for adding an entity to database:
controller:
[HttpPost]
[Route("api/v1/catalog/products/pictures")]
[ProducesResponseType((int)HttpStatusCode.Created)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> UploadPicture([FromForm]PictureViewModel pic)
{
try
{
var result = await _service.Add(pic);
if (result.HasErrors)
{
return BadRequest(result.Errors);
}
return CreatedAtAction(nameof(GetById), result);
}
catch (Exception ex)
{
return BadRequest(ex.ToString());
}
}
service:
public async Task<ServiceResultWithoutBaseEntity<Picture>> Add(PictureViewModel newItem)
{
var result = new ServiceResultWithoutBaseEntity<Picture>();
result.Errors.AddRange(Validate(newItem));
if (result.HasErrors)
return result;
var item = await newItem.MapToEntity(new Picture());
_context.Pictures.Add(item);
await _context.SaveChangesAsync();
result.EntityResult = item;
return result;
}
helper:
public async static Task<Picture> MapToEntity(this PictureViewModel source, Picture entity)
{
if (source == null || entity == null)
return null;
if (source.FileForUpload != null || source.FileForUpload.Length != 0)
{
AzureBlobExtensions abe = new AzureBlobExtensions();
string folderValue = string.Concat(entity.ID.ToString().ToLower(), "/", DateTime.Now.ToString("yyyyMMddHHmmss"), source.FileForUpload.FileName);
var fileUrl = await abe.UploadFile(source.FileForUpload, folderValue, Path.GetExtension(source.FileForUpload.FileName), "Picture");
entity.VirtualPath = fileUrl;
}
else
{
entity.VirtualPath = source.FileUrl;
}
entity.FileName = source.FileName;
entity.SeoFilename = source.SeoFilename;
entity.AltAttribute = source.AltAttribute;
entity.TitleAtrribute = source.TitleAtrribute;
entity.MimeType = source.MimeType;
entity.IsNew = source.IsNew;
return entity;
}
product table
picture table
productPicture table
Hi I am tryin to use Transactions in my application which coded in MVC.net
I have my dbcontext in a layer and I reach it from a business layer. When I run the code its not giving me any errors but its also not making the transaction at all.
This is my context
public class DB : IDisposable
{
public DB()
{
}
private RootDYSContext _ctx = null;
public RootDYSContext ctx
{
get
{
if (_ctx == null)
_ctx = new RootDYSContext();
return _ctx;
}
set
{
_ctx = value;
}
}
public bool Commit()
{
try
{
ctx.SaveChanges();
}
catch (Exception exp)
{
Mesaj = exp.Message;
return false;
}
return true;
}
}
And this is how I am tryin to do transaction which based on here "https://learn.microsoft.com/en-us/ef/core/saving/transactions"
public bool CreateKullanici(VMKullanici
KullaniciData,List<VMRol>RolDataList,VMRol AnaRolData)
{
string mesaj = "";
int kullanici_id;
using (RootDBHelper.DB db = new RootDBHelper.DB())
{
using (var ctx = new RootDBLayer.RootDYSContext())
{
using (DbContextTransaction dbContextTransaction =
ctx.Database.BeginTransaction())
{
try
{
kullanici_id = SaveKullanici(KullaniciData, out
mesaj);
foreach(VMRol rol in RolDataList)
{
VMKullaniciRol KullaniciRolInsertData = new
VMKullaniciRol();
KullaniciRolInsertData.kullanici_id =
kullanici_id;
KullaniciRolInsertData.rol_id = rol.rol_id;
if (rol.rol_id == AnaRolData.rol_id)
KullaniciRolInsertData.ana_rol_mu =
(int)RConstants.EvetHayir.Evet;
else
KullaniciRolInsertData.ana_rol_mu =
(int)RConstants.EvetHayir.Hayir;
bKullaniciRol.SaveKullaniciRol(KullaniciRolInsertData, out mesaj);
}
/*Edit:I think this line made confusion I put this to make sure rollback
dbContextTransaction.Rollback(); */
dbContextTransaction.Commit();
return true;
}
catch
{
dbContextTransaction.Rollback();
return false;
}
}
}
}
}
I expect when I run this I shouldnt get any record at all.I seriously stucked because I dont get any error or any hint at all and this method keeps saving data regardless of rollback.
Thank you in advance.
Edit: I do my save changes part on the insert methods
Adding also code examples for the methods
public int SaveKullanici(VMKullanici KullaniciData, out string mesaj)
{
using (RootDBHelper.DB db = new RootDBHelper.DB())
{
mesaj = "";
PKullanici pKullanici = new PKullanici();
if (KullaniciData.kullanici_id == default(int))
pKullanici.InsertKullanici(db.ctx, KullaniciData);
else
pKullanici.UpdateKullanici(db.ctx, KullaniciData);
if (db.Commit())
{
return KullaniciData.kullanici_id;
}
else
{
mesaj = db.Mesaj;
return -1;
}
}
}
public void InsertKullanici(RootDYSContext ctx, VMKullanici KullaniciData)
{
ctx.TKullanici.Add(KullaniciData.TKullanici);
}
I think your problem is that you do commit and then you want to rollback but you should one thing commit or rollback.
In addition I cant see in your code where you actually doing transaction.commit. Your code has commit function but commit != savechanges.
Idea of transactions (there are different type but) is that you save data to database do some validation or operations and then you say well it looks ok commit or there is an error do rollback.
Also note if you are not do not commit or do rollback then your identity field will get incremented no matter what