Why would this query be returning null? - c#

I am working on setting up database storage for a game project I am working on for school, and am at the very beginning of doing so. I am using MongoDB at the suggestion of our sponsor. I have successfully implemented inserting a list of names with individual indices, but I cannot get it to return them. The code I am using is as follows.
public string getName(int id) {
var query = Query.EQ("_index", id);
if (Names.FindOne(query) != null) return (Names.FindOne(query)).FirstName;
else return "Error";
}
I have now determined the problem is that the objects aren't being saved. My code for doing so is
public void storeName(string name, int number) {
Name Insert = new Name{FirstName = name, index = number};
var query = Query.EQ("_FirstName", name);
if (Names.FindOne(query) == null) { Names.Save<Name>(Insert); Console.WriteLine(Insert.index+" "+Insert.FirstName); }
else {Console.WriteLine("Bork"); }
}
And the Name object is automapped.

I solved my problem. The index and FirstName fields needed to not have the underscores.

Related

SaveChanges problem in N-Tier Architecture

Normally, with MVC I use db.savechanges() method after I do some processes. But check the below code when I use N-Tier Architecture in everyloop its gonna insert in this way but I dont want it. I have to check all the items first. If there is no problem then I have to insert it all together.
foreach (var item in mOrderList)
{
MOrder mOrder = new MOrder();
mOrder.StatusAdmin = false;
mOrder.Date = DateTime.Now;
mOrder.StatusMVendor = "Sipariş alındı.";
mOrder.HowMany = item.HowMany;
mOrder.MBasketId = item.MBasketId;
mOrder.MProductId = item.MProductId;
mOrder.MVendorId = item.MVendorId;
mOrder.WInvestorId = item.WInvestorId;
MProduct mprostock = _imProductService.GetMProductById(item.MProductId);
if (mprostock.Stock<=0)
{
return ReturnErrorAndSuccess(HttpStatusCode.NotFound, "MProduct", mprostock.Name + " ürününde stok kalmadığı için işlem tamamlanamadı.");
}
_imOrderService.InsertMOrder(mOrder);
}
all you have to do is:
first you should define a method that get list of mProductId and then return list of MProduct.
after that you should check if there is any record with Stock<=0 then return your error.
-also for your insert you should define a method that get list of MOrder and return appropriate datatype for example Boolean.
public List<MProduct> GetMProductByIds(List<MProductId> mProductId)
{
//getting record code
}
public bool AddMOrder(List<MOrder> mOrder)
{
//inserting record code
}

How to delete elements from sql database based on a date using c# .net

I have this Service that works to delete one (1) row from the database (Sorry for any lingo errors.):
public bool DeleteSchedulesFromDate(DateTime objDateTime)
{
var result = _db.Schedules.FirstOrDefault(x => x.AppointmentDateEnd <= objDateTime);
if (result != null)
{
_db.Schedules.Remove(result);
_db.SaveChanges();
}
else
{
return false;
}
return true;
}
This as the calling function:
private void DeleteSchedules(string dtEnd)
{
deleteScheduleDate = dtEnd;
DateTime _dtEnd;
if (DateTime.TryParse(dtEnd, out _dtEnd))
{
var result = #Service.DeleteSchedulesFromDate(_dtEnd);
schedules.Clear();
schedules = Service.GetSchedules();
if (result)
{
this.ShouldRender();
}
}
}
But how do I change it to delete all rows that matches the passed DateTime object?
I have tried :
to change it to a List, but then the bool doesn't work.
set a loop in the Service, but can't make it run correctly.
set a loop in the function call, but can't make it work either.
to google and look up other posts on SO, but found no match.
Instead of searching for the first match with FirstOrDefault you should get all valid result into a List (Where + ToList) and delete all of them (RemoveRange)
var result = _db.Schedules.Where(x => x.AppointmentDateEnd <= objDateTime).ToList();
if (result.Any())
{
_db.Schedules.RemoveRange(result);
_db.SaveChanges();
}

C# Entity Framework and stored procedures

I made my database with its stored procedures then attached it with my project Entity Framework database-first.
This function to insert a company info and return its id back and insert it to another table in relation with company table
public string InsertCompany(company company, out int index)
{
try
{
using (vendors_managerEntities db = new vendors_managerEntities())
{
db.companies.Add(company);
db.SaveChanges();
index = company.id_company;
return $"{company.name_company} Is Saved";
}
}
catch (Exception ex)
{
index = 0;
return ex.Message;
}
}
But when I tried to my stored procedure which has been created in database, I couldn't return any value the id always be 0
public string InsertCompany(company company, out int index)
{
try
{
using (vendors_managerEntities db = new vendors_managerEntities())
{
db.SP_insert_companies(company.name_company, company.website_company, company.adress_company, company.county_company, company.decription_company);
index = company.id_company;
return $"{company.name_company} Is Saved";
}
}
catch (Exception ex)
{
index = 0;
return ex.Message;
}
}
I read that I can make it in SQL but I'm looking for a solution in C#, so I opened the stored procedure definition in C# and found the following code and was thinking if can I change its return value because it's not return the id value
public virtual int SP_insert_companies(string name, string website, string address, string country, string description)
{
var nameParameter = name != null ?
new ObjectParameter("name", name) :
new ObjectParameter("name", typeof(string));
var websiteParameter = website != null ?
new ObjectParameter("website", website) :
new ObjectParameter("website", typeof(string));
var addressParameter = address != null ?
new ObjectParameter("address", address) :
new ObjectParameter("address", typeof(string));
var countryParameter = country != null ?
new ObjectParameter("country", country) :
new ObjectParameter("country", typeof(string));
var descriptionParameter = description != null ?
new ObjectParameter("description", description) :
new ObjectParameter("description", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("SP_insert_companies", nameParameter, websiteParameter, addressParameter, countryParameter, descriptionParameter);
}
Please tell me if there's a solution in C# or should I go back to old code without stored procedure in that case?
The issue is that you are using a stored procedure to insert the company entity which I suspect does not cause the object to be refreshed by the context:
db.SP_insert_companies(company.name_company, company.website_company, company.adress_company, company.county_company, company.decription_company);
You then try to get the id from the object which is 0 because it hasn't been refreshed:
index = company.id_company;
If you insist on using a stored procedure, what I would suggest is that you have the SP return the id of the company, then grab it from the call and use that as the value of index:
index = db.SP_insert_companies(company.name_company, company.website_company, company.adress_company, company.county_company, company.decription_company);
Once you modify the SP, make sure to update the definition in your code so it knows to make a function that returns a value.
If you prefer to have it in the object itself, then make sure to update it manually, although I don't recommend this as the object is not in true sync with the database:
index = db.SP_insert_companies(company.name_company, company.website_company, company.adress_company, company.county_company, company.decription_company);
company.id_company = index;
Based on what you're saying it's automatically going to the "Catch" and then the index is already set to 0. So chances are your code elsewhere, not listed is messing up. I suspect wherever your code for saving the company information isn't saving properly. Try manually inputting a company into the DB and then check it with your program. If it returns that it's "Saved" then you know your problem isn't within this method and is a result of your saving method.

Add to exisiting Database instance from MVC Controller

Private BookingDB db = new BookingDB();
Private MonthDb mdb = new MonthDB();
if (ModelState.IsValid)
{
String date = (booking.Start_Date).ToString();
var check = from b in mdb.months
where b.BookedDays.Contains(date)
select b;
if (check != null)
{
return View(booking);
}
else
{
booking.Reservation_Owner = User.Identity.Name;
//Add booking.Start_Date to mdb.Entry(check).BookedDays
mdb.SaveChanges();
db.bookings.Add(booking);
db.SaveChanges();
return RedirectToAction("Index");
}
}
I've got this code that on creation of a new booking, will check that no exisiting bookings have already been made on or around that specific day.
if the day to be booked is not already been booked (ie exists under BookedDays in mdb.months) then i wish to add the Start_Date of the booking, to the BookedDays string in the mdb.months database (the mdb.month database is just a list of the 12 months)
at first i tried using mdb.Entry() to add to that specific month instance, however i cannot get it to work.
the error is:
the model does not have a definition for BookedDays
what do?
Your checking that check is null
if (check != null)
{
return View(booking);
}
else
{
and then using check anyway:
check.BookedDays
check is null and therefore does not contain any BookedDays. I'm guessing your null check is the wrong way around and should be
if (check == null)
{
return View(booking);
}
else
{
That said your problem is not well explained so I'm not sure.

No results from SQLite when trying to select by PrimaryKey using sqlite-net

For this example, I've defined the following class, which is saved inside an SQLite database:
[SQLite.AutoIncrement, SQLite.PrimaryKey, SQLite.Indexed]
public int ID { get; set; }
[SQLite.Indexed]
public string ImageName { get; set; }
I'm using the insert command supplied with sqlite-net, and it works:
SQLiteAsyncConnection CurrentConnection = new SQLiteAsyncConnection("DB");
int result = await CurrentConnection.InsertAsync(this);
Afterwards, I'm trying to select data from the SQLite DB.
List<Image> result = new List<Image>();
if (ImageName != null)
{
query = CurrentConnection.Table<Image>().Where(i => i.ImageName == ImageName);
result = await query.ToListAsync();
}
if (ID != null && ID > 0)
{
query = CurrentConnection.Table<Image>().Where(i => i.ID == ID);
result = await query.ToListAsync();
}
if (result.Count > 0)
{
LoadFromResult(result[0]);
return;
}
When selecting by ImageName, all works well and I get the results I need. However, when trying to select by ID, no results are selected.
I know the image with the given ID exists since I've just inserted it and checked the ID afterwards, but for some reason this just does not work.
Am I completely blind and missed a small letter here? Has anyone used SQLite-net to try and select by Primary key?
//Edit
Also tried this, which did not work:
var query1 = await CurrentConnection.QueryAsync<Image>("select * from Image where ID = ?", ID);
if (query1.Count > 0)
{
LoadFromResult(query1[0]);
return;
}
//edit 2
I've got a bit of a hunch on this - when I insert the image, the ID does get set to some ID, however when I select all the images in the DB, all of them have an ID of 0.
Any idea on why this could happen?
I think your problem might be with AutoIncrement attribute for your class.
Try removing the AutoIncrement attribute and see, if you can find the image by id.
I think what's happening is that the AutoIncrement attribute is setting the Id, overriding the id you create.
For Example
Let's say you create an instance of your MyImage with:
MyImage i = new MyImage() { Id=5,
ImageName="imageName"}
When you run,CurrentConnection.InsertAsync(i) (on an empty table), the entry inserted to the database has ID 1, not 5.
Hope that helped

Categories

Resources