ASP.NET LINQ (C#) UPDATE SYNTAX - c#

I am using LINQ to Entities in an ASP.NET C# app. The below code is my attempt to update (or reset, really) a value 'AvgRideTime' in my sql db to null. However it seems to do nothing, no errors, just nothing. Any thoughts?
protected void ResetAvgRT_Click(object sender, EventArgs e)
{
using (RamRideOpsEntities myEntities = new RamRideOpsEntities())
{
var avgTime = (from a in myEntities.AdminOptions
select a.AvgRideTime).First();
if (avgTime != null)
{
avgTime = null;
myEntities.SaveChanges();
}
}
}

var avgTime = myEntities.AdminOptions.First();
if (avgTime != null)
{
avgTime.AvgRideTime = null;
myEntities.SaveChanges();
}
Try the above code.

avgTime this is link to object and when you set avgTime = null, avgTime no referenced to object, but myEntities.AdminOptions contains this object.

Maybe the avgTime gets a null value.

Try the following code
protected void ResetAvgRT_Click(object sender, EventArgs e)
{
using (RamRideOpsEntities myEntities = new RamRideOpsEntities())
{
var avgTime = (from a in myEntities.AdminOptions
select a).First();
if (a.avgTime != null)
{
a.avgTime = null;
myEntities.Entry(a).State = EntityState.Modified;
myEntities.SaveChanges();
}
}
}

Related

Fetching 1 record based on the name of the logged in User and show these values in txt boxes (c#)

I Want to fetch 1 record based on the name of the logged in User and show these values in txt boxes (c#)
I am a bit stuck on how to handle this, any help would be welcome.
Currently I am trying to fetch it using LINQ:
DAL.VindjekindjeDataContext dc = new DAL.VindjekindjeDataContext();
public object GetCompleteOuder(string p)
{
//var query = (from TOUD in dc.TOUDs where TOUD.Ouderid == p select TOUD).Single();
return (from TOUD in dc.TOUDs where TOUD.Voornaam.Equals(p) select TOUD ).First();
}
protected void Page_Load(object sender, EventArgs e)
{
string naam = User.Identity.Name;
object parent = new object();
parent = Ouder.GetCompleteOuder(naam);
Type typB = parent.GetType();
NaamTxt.Text = (string)typB.GetField("Naam").GetValue(parent);
}
However I get the following error:
System.NullReferenceException: Object reference not set to an instance of an object.
There is just too much going wrong here.
Your exception is possibly caused by a parent (ouder in Dutch) which has a null value for Voornaam)
You instantiate an object parent which is useless since you overwrite it the next line.
Your parent variable should be strongly typed. That will prevent you to need reflection to get the Naam property. This, by the way, is another possible source for your NullReferenceException.
Perhaps something like this
public bool GetCompleteOuder(out TOUD user, string p)
{
user = new TOUD();
try
{
db.TOUDS.SingleOrDefault(t => t.Voornaam == p);
return true;
}
catch
{
return false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
string naam = User.Identity.Name;
TOUD user;
if(GetCompleteOuder(out user, naam))
{
NaamTxt.Text = user.<fieldname>;
}
else
{
NaamTxt.Text = string.empty;
}
}
Final working code:
DAL.VindjekindjeDataContext dc = new DAL.VindjekindjeDataContext();
public bool GetCompleteOuder(out DAL.TOUD user, string p)
{
user = new DAL.TOUD();
try
{
dc.TOUDs.SingleOrDefault(t => t.Voornaam == p);
user = (from TOUD in dc.TOUDs where TOUD.Voornaam.Equals(p) select TOUD).Single();
return true;
}
catch
{
return false;
}
}
//page load behind aspx page
OuderDAL Ouder = new OuderDAL();
protected void Page_Load(object sender, EventArgs e)
{
string naam = User.Identity.Name;
DAL.TOUD user;
if(Ouder.GetCompleteOuder(out user, naam))
{
/*vullen van de velden met de gegevens voor de ingelogde gebruiker*/
NaamTxt.Text = user.Naam;

Reloading and Updating using Entity Framework and DBContext

Ok so I have tried a few things and keep getting stuck. I had the update button working at one point and now it will not update. The delete button will work and delete records but I can not get the gridview to refresh after the record is deleted. I also want the gridview to reload after the update button is pressed and the record is updated. Here is what I have:
protected void btnDelete_Click(object sender, EventArgs e)
{
switch (btnDelete.Text)
{
case DeleteButton:
try
{
if (txtLocationName.Text != null && txtSubAccountName.Text != null)
{
Location locationCheck = _context.Locations.ToList()
.First(x => x.Name == txtLocationName.Text && x.SubAccount == txtSubAccountName.Text);
if (locationCheck != null)
{
Location n = new Location
{
Id = grdvwLocationList.SelectedIndex,
Name = txtLocationName.Text,
SubAccount = txtSubAccountName.Text
};
_context.Locations.Remove(n);
_context.SaveChanges();
}
}
}
catch (Exception)
{
lblLocationNameNotification.Text = "Please type in a location/sub-account or select a location/sub-account that doesn't have a asset to delete.";
txtLocationName.Text = "";
txtSubAccountName.Text = "";
}
break;
case CancelButton:
Reload();
break;
}
}
public void PopulateLocationGridView()
{
var locations = _context.Locations.Where(l => l.CompanyId == CompanyId)
.OrderBy(l => l.Name)
.ToList();
grdvwLocationList.DataSource = locations;
grdvwLocationList.DataBind();
if (locations.Count > 0)
{
grdvwLocationList.SelectedIndex = 0;
RowSelected();
}
else
{
txtLocationName.Text = "";
txtSubAccountName.Text = "";
}
}
The add button works just fine it just seems to be refreshing the grid view
I have the following exampe working in a winforms application
The trick is the dset.local
private void Form1_Load(object sender, EventArgs e)
{
var dset = Db.Tasks; // Db is my context.
DbSet<Task> qry = dset;
qry.Load();
bindingSource1.DataSource =dset.Local.ToBindingList();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Debug.Print(Db.Tasks.Count().ToString());
bindingSource1.EndEdit();
Db.SaveChanges();
}
After working on it last night I knew there was something that I was missing. I ended up going about it like this:
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
_context = new IMSDBContext();
switch (btnDelete.Text)
{
case DeleteButton:
if (txtLocationName.Text != null && txtSubAccountName.Text != null)
{
Location location = _context.Locations.ToList()
.First(x => x.Name == txtLocationName.Text && x.SubAccount == txtSubAccountName.Text);
_context.Locations.Remove(location);
_context.SaveChanges();
PopulateLocationGridView();
grdvwLocationList.SelectedIndex = 0;
RowSelected();
}
break;
case CancelButton:
Reload();
break;
}
}
catch (Exception ex)
{
lblLocationNameNotification.Text = ex.Message;
}
finally
{
if (_context != null)
{
_context.Dispose();
}
}
}
I had tried to use the PopulateLocationGridView() and RowSelect() methods by themselves and it was still having trouble. I ended up putting in the grdvwLocationList.SelectedIndex = 0; in to set the selected index on the first index in the list instead of the index of the record that I just deleted. That is where I was having trouble. I thought that the SelectRow() would reselect the index again but I had to reset it back to another index. If there are any questions or comments please feel free. I am still learning and would like all of the advise that I can get.

Linq update query

I want to update an existing record. I also have debugged my code. The int id variable gets the value, but I don't know why my record doesn't updated.
SQLDBDataClassesDataContext dContext = new SQLDBDataClassesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
//if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["fname"]))
{
FirstNameTextBox.Text = Request.QueryString["fname"];
}
if (!string.IsNullOrEmpty(Request.QueryString["lname"]))
{
LastNameTextBox.Text = Request.QueryString["lname"];
}
if (!string.IsNullOrEmpty(Request.QueryString["cellnum"]))
{
CellNumberTextBox.Text = Request.QueryString["cellnum"];
}
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
var updatequery1 = dContext.PersonalDetailTables
.Where(pd => pd.ID == id).SingleOrDefault();
if (updatequery1 != null)
{
updatequery1.FirstName = FirstNameTextBox.Text;
updatequery1.LastName = LastNameTextBox.Text;
updatequery1.CellNumber = CellNumberTextBox.Text;
dContext.SubmitChanges();
}
}
if (updatequery1 != null)
is updatequery1 null? If it's now, it'll just skip right over. Setup a breakpoint and step through.
Alternatively, change .SingleOrDefautl to .Single instead. This way if nothing's found, u'll get an exception, and u'll know what's up.
Call dContext.InsertOnSubmit(fooentity) method before calling dContext.SubmitChanges();.
For example.
var ctx = DB.fooDB;
fooobj.fooName= bar.fooName;
fooobj.fooID= bar.fooID;
if (fooobj.fooID== 0)
ctx.Locations.InsertOnSubmit(bar);
ctx.SubmitChanges();
I`ve got my Solution..
the only problem was of if(!ispostback) issue.
context.InvProductStockMasters
.Update(ps => ps.LocationID.Equals(invStockAdjustmentHeader.LocationID)
&& ps.ProductID.Equals(invStockAdjustmentDetail.ProductID),
ps => new InvProductStockMaster
{ Stock = ps.Stock - invStockAdjustmentDetail.OrderQty });

Updating data into Database

I have problems adding data into the database. The code that I have written could only update the shiftTiming_Start but not the shiftTiming_Stop. Can someone please help take a look at my code and see what went wrong. Thanks a lot.
private void btnUpdate_Click(object sender, EventArgs e) {
using (testEntities Setupctx = new testEntities()) {
var toBeUpdated = txtStart.Text;
var toBeUpdated1 = txtStop.Text;
shifthour updateShift = new shifthour();
updateShift = Setupctx.shifthours.FirstOrDefault(u => u.shiftTiming_start == toBeUpdated);
updateShift = Setupctx.shifthours.FirstOrDefault(p => p.shiftTiming_stop == toBeUpdated1);
updateShift.shiftTiming_start = txtStart.Text;
updateShift.shiftTiming_stop = txtStop.Text;
Setupctx.SaveChanges();
txtStart.Text = "";
txtStop.Text = "";
MessageBox.Show("Shift Timing Has Been Updated.");
}
}
Assuming I'm following you correctly (I would recommend using more meaningful variable names), update the code as follows:
private void btnUpdate_Click(object sender, EventArgs e) {
using (testEntities Setupctx = new testEntities()) {
var toBeUpdatedStart = txtStart.Text;
var toBeUpdatedStop = txtStop.Text;
shifthour updateStartShift;
shifthour updateStopShift;
updateStartShift = Setupctx.shifthours.FirstOrDefault(u => u.shiftTiming_start == toBeUpdatedStart);
updateStopShift = Setupctx.shifthours.FirstOrDefault(p => p.shiftTiming_stop == toBeUpdatedStop);
if (updateStartShift != null)
{
updateStartShift.shiftTiming_start = txtStart.Text;
}
if (updateStopShift != null)
{
updateStopShift.shiftTiming_stop = txtStop.Text;
}
Setupctx.SaveChanges();
txtStart.Text = "";
txtStop.Text = "";
MessageBox.Show("Shift Timing Has Been Updated.");
}
}

Passing value from labelbox to a linq query

Hello guys i am new to linq and so is in .net. i want pass a value from label box to a linq query as parameter.below is the code ...
namespace PblCard.PublicWeb
{
public partial class Cardno : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
{
if (!IsPostBack)
{
if (Page.User.IsInRole(SecurityEngine.Roles.Customer))
{
Customer customer = new CustomerEngine().GetCustomerByEmail(Page.User.Identity.Name);
if (customer == null)
throw new ApplicationException(Properties.Resources.CustomerNotFound);
lblCardNo.Text = customer.CardNumber;
}
}
}
}
protected void ASPxButton2_Click(object sender, EventArgs e)
{
string panno = lblCardNo.Text;
using (Entities query = new Entities())
{
var txn = from p in query.TRANSACTIONs
.Where(x => x.PAN == panno)
select p;
GridView1.DataSource = txn;
GridView1.DataBind();
}
}
}
}
but when binding to grid i am not getting any output. but if i use this
protected void ASPxButton2_Click(object sender, EventArgs e)
{
string panno = lblCardNo.Text;
using (Entities query = new Entities())
{
var txn = from p in query.TRANSACTIONs
.Where(x => x.PAN == ("234567"))
select p;
GridView1.DataSource = txn;
GridView1.DataBind();
}
}
}
the grid is showing data. How should I write the query?
Databinding does not work with raw LINQ queries.
You need to write GridView1.DataSource = txn.ToList();
Add break point on panno to check if there is value pass from lblCardNo.Text.
string panno = lblCardNo.Text; <-- here
var txn = (from p in query.TRANSACTIONs
where Convert.ToString(p.PAN.ToString) == Convert.ToString(panno) <-- here
select p).ToList();
GridView1.DataSource = txn;
GridView1.DataBind();
then try to point to txn and check' results view' if it has a data.
Regards

Categories

Resources