I'm trying to make a database. I made a form and I want to get the data from that. Everything seems okay, but my database didn't get the update and didn't change. I'm using a local database. I tried to change "Copy to output directory" but nothing happened... The SubmitChanges seems ok: I get the Message, but after the program is closed the database doesn't contain the new data... I saw a lot of posts with similar problems, but I didn't find a solution.
My Code:
private void felvetButton_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
if (f2.ShowDialog() == DialogResult.OK)
{
Match m = new Match();
try
{
m.datum = f2.datumTextBox.Text;
m.mod_fk = Convert.ToInt32(f2.modTextBox.Text);
m.acc_fk = Convert.ToInt32(f2.accTextBox.Text);
m.champion = f2.champTextBox.Text;
m.szerep_fk = Convert.ToInt32(f2.roleTextBox.Text);
m.kimenet = f2.resultTextBox.Text;
m.mhossz = f2.lengthTextBox.Text;
m.kill = Convert.ToInt32(f2.killTextBox.Text);
m.death = Convert.ToInt32(f2.deathTextBox.Text);
m.assist = Convert.ToInt32(f2.assistTextBox.Text);
m.kda = float.Parse(f2.kdaTextBox.Text);
m.killpart = float.Parse(f2.kpTextBox.Text);
m.farm = Convert.ToInt32(f2.farmTextBox.Text);
m.ward = Convert.ToInt32(f2.wardTextBox.Text);
m.redward = Convert.ToInt32(f2.redwTextBox.Text);
db.SubmitChanges();
MessageBox.Show("New match added to the database!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Don't you have to make the entity layer aware of this new object? I imagine you need to call something like this for new entities:
db.Matches.InsertOnSubmit(match);
Its perfectly fine to load entities from the database via this entity layer, modify them, and then use db.SubmitChanges() because the entity layer already knows about existing objects! How is it supposed to know about this new object if the entity layer doesn't have any reference to it?
Related
I have probem when use thread in winform.
I have error when debug program.
My Application throw exception when start program.
I define class RunInUIThread is:
private void RunInUIThread(Delegate method)
{
this.BeginInvoke(method);
}
And in RunInUIThread method like:
BaiXeBUS baixe = new BaiXeBUS();
RunInUIThread(new ThreadStart(delegate ()
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}));
Why my code not work. Someone can explain me and how to fix problem?
Thank all reader!!!
What I mean is trying to run this block of code without the ThreadStart
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}
This is to debug your code within the main thread.
#JoelLegaspiEnriquez, your recommned me to remove [STAThread] in Program.cs?
If I comment this line. This have problem in control AxLiveX1 is control of camera ip.
The txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString(); is Guid type with 16byte: 8d58d690-6b71-4ee8-85ad-006db0287bf1.
But i assign txtKhuVucBai to Guid type is:
private Guid mCurrentCardIDBlock1;
public Guid CurrentCardIDBlock1
{
get { return mCurrentCardIDBlock1; }
}
The mCurrentCardIDBlock1 is type of RFID reader with 32 character random.
I am using linq to sql in a windows form application. there is a bug that I couldn't find the solution until now!
partial void OnAmountChanging(int? value)
{
OrderLog lg = new OrderLog()
{
Date = DateTime.Now,
IPAddress = System.Net.Dns.GetHostAddresses(Environment.MachineName)[0].ToString(),
NewData = value,
OldData = this.Amount,
Status = "Changed",
User = User.CurUser,
Order = this // each Order has one-to-many relation to OrderLog entity.
};
}
this is run as soon as the value of AMOUNT changes in datagridview.
after closing the form I try to save the created log to Database:
db.SubmitChanges();
then I face this error :
An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported
is there any solution?
I was successfully able to save data to the Sql Server database, using an Entity Data Model, as follows:
MEDIANEntities db = new MEDIANEntities();
tblCountry objTable = new tblCountry();
objTable.Name= txtName.Text.Trim();
objTable.CreatedDate = System.DateTime.Now;
db.AddTotblCountries(objTable);
db.SaveChanges();
The idea now, is to use the EDM in a class library, so that it can be consumed in other projects (a tier architecture basically). I have created a Class library - 'MedianContext' and then created a new edmx file inside it - 'MedianModel'. And then another class library - 'MedianDAL'. Added the reference of MedianContext to it.
Unable to access properties of objcontext and tb. How can I proceed further.
If it helps, when adding the reference to MedianDAL, the MediaContext.dll was inside the debug folder instead of Release folder, as seen in many examples.
Have you tried it with Linq2Entities?
e.g.:
try
{
using (var medianEntities = new MedianModel.MEDIANEntities())
{
//Do any LinqToEntity-Expressions
}
}
catch(Exception)
{
//ErrorHandling
}
That works for me.
I also have my .edmx files in a different project and just added a reference to this.
Edit:
Of course you have to put this code into a method-body.
Here is a simple example:
public List<Map> GetAllMaps()
{
var Maps = new System.Collections.Generic.List<Map>();
try
{
using (var mapEntities = new Model.MapEntities())
{
var MyMaps= (from M in mapEntities.Maps
orderby M.Description
select M.MapID, M.Description);
foreach (var Map in MyMaps)
{
Maps.Add(Map);
}
}
return Maps;
}
catch (System.Exception Exc)
{
Log.Err(string.Format("Error: {0}", Exc));
throw new System.Exception(Exc.ToString());
}
}
Probably because you are trying to access the properties while in the context of the class ? Create constructor for this class and access the properties from there:
public Test
{
tb....
}
I am experimenting with Azure and am running into an issue I cannot seem to find an answer to.
I am running a linq query to update Azure Database with changes to a record but for some reason the changes are not being noted or submitted to the database. The code I am running is as follows:
DataClasses1DataContext update = new DataClasses1DataContext();
Company extra = update.Companies.Single(p => p.ID == Convert.ToInt32(Request.QueryString["ID"]));
extra.companyName = txtCompanyName.Text;
extra.address1 = txtAddress1.Text;
extra.address2 = txtAddress2.Text;
extra.address3 = txtAddress3.Text;
extra.address4 = txtAddress4.Text;
extra.town = txtTown.Text;
extra.county = txtCounty.Text;
extra.postCode = txtPostCode.Text;
extra.billingEmail = txtBillingEmail.Text;
extra.facebook = txtFacebook.Text;
extra.fax = txtFaxNumber.Text;
extra.faxArea = txtFaxArea.Text;
extra.faxCountry = txtFaxCountry.Text;
extra.linkedIn = txtLinkedIn.Text;
extra.mainEmail = txtMainEmail.Text;
extra.mainPhone = txtMainLineNumber.Text;
extra.mainPhoneArea = txtMainLineArea.Text;
extra.mainPhoneCountry = txtMainLineCountry.Text;
if (drpMarketing.Text == "No")
{
extra.marketingYesNo = 0;
}
else
{
extra.marketingYesNo = 1;
}
extra.salesEmail = txtSalesEmail.Text;
extra.twitter = txtTwitter.Text;
extra.website = txtWebsite.Text;
update.SubmitChanges();
What I am noticing by setting break points is that if I load the page and then change some data then the new data is not being reflected when this code is called (it is in a btnUpdate_Click event)
So When the submitChanges() is used then the new data is not present to submit. Any help appreciated.... I think I have looked at this for so long it needs some fresh eyes lol.
Are you sure you are not repopulating your form OnPostback with the original data (re-selected from the database) so that the linq update actually works, but you are always submitting the most recent database data back to the database.
In other words are you sure you are only populating your form
if(!Page.IsPostback)
{
//populate the form
}
this will preserve user amends when a postback happens.
Have you tried to wrap the SubmitChanges in a try block? Maybe it is throwing an exception. Here is how it is documented to do updates which is very similar to what you are doing:
http://msdn.microsoft.com/en-us/library/bb399339.aspx
Also, does this work against a local SQL Server database or SQL Express database?
So, here is my hopefully unique spin on this common problem.
I do my query, get my objects then pass the object into a form where it populates the form with the data from the object (this is not passed in by reference).
I then edit the values of the object that was queried (via the form) and then return a new object constructed from the values in the form.
I then want to update this to the database. Attach does nothing (runs but does not update). SubmitChanges also does nothing (and both do nothing when used together).
What am I missing?
Update: here is the code I am using:
// In constructor
_dataMap = new DataMapDataContext();
_addresses = _dataMap.AddressItems
.Where(address => address.InsertUserName == _currentUser.Name).ToList();
public void EditButtonClick()
{
using (AddAddressForm form = new AddAddressForm(_addresses[_currentAddress]))
{
form.Text = "Edit Address";
if (DialogResult.OK == form.ShowDialog())
{
_addresses[_currentAddress] = form.Item;
_dataMap.SubmitChanges();
DisplayItem();
}
}
}
You'll need to get the record from the database, update it's values and then call SubmitChanges()
using(MyDataContext db = new MyDataContext())
{
// get the record
Product dbProduct = db.Products.Single(p => p.ID == 1);
// set new values
dbProduct.Quantity = 5;
dbProduct.IsAvailable = false;
// save them back to the database
db.SubmitChanges();
}
Turns out I was doing almost everything right.
I just needed to pass in the object I was editing by reference. That way when it got changed, it was not a new object that was returned, but the same one (that Linq-to-SQL already knew about.)
These are the two lines from the code above that got changed:
AddressItem itemToEdit = _addresses[_currentAddress];
using (AddAddressForm form = new AddAddressForm(ref itemToEdit))