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))
Related
public string UpdateCateter(string json)
{
try
{
jss.MaxJsonLength = 900000000;
conexion.Configuration.ValidateOnSaveEnabled = false;
conexion.Configuration.AutoDetectChangesEnabled = false;
conexion.Configuration.LazyLoadingEnabled = false;
conexion.Configuration.ProxyCreationEnabled = false;
dynamic newValues = jss.DeserializeObject(json);
int codigo = Convert.ToInt32(newValues["id"]);
cateter_mahurka_web data = conexion.cateter_mahurka_web.Find(codigo);
if (data != null)
{
foreach (var property in data.GetType().GetProperties())
{
var newValue = newValues[property.Name];
if (newValue != null)
{
var rspre3 = property.SetValue(data, Convert.ChangeType(newValue, property.PropertyType));
var rspre1 = conexion.Entry(data).State;
}
}
var rspre = conexion.Entry(data).State;
var rs = conexion.SaveChanges();
return jss.Serialize(rs > 0);
}
return jss.Serialize("No se encontro ningun registro");
}
#region catch...
}
I hope u can help me, Im trying to update a database record using Entity Framework. The New Values are being stored into an object called "newValues". Then, it finds a record in the database with the specified "id" value and stores it in the "data" object.
Next, the code loops through each property in the "data" object and compares it to the corresponding property in the "newValues" object. If the property in "newValues" is not null, the code sets the value of the corresponding property in the "data" object to the value in "newValues".
Finally, the code saves the changes to the database by calling the "SaveChanges" method on the database context. The result of this method call is then serialized and returned as a string, indicating whether the update was successful or not.
It is expected that the code would update the database record with the new values provided in the "newValues" object and return a string indicating whether the update was successful or not.
But in the line var rspre = conexion.Entry(data).State; im getting unchanged so it is not updating can u help me pls.
Although I am making modifications to a database instance, I am encountering an issue where the changes are not being detected by the system. However, I have found a solution to this problem by adding the following line of code to my implementation: "conexion.Entry(data).State = EntityState.Modified;". By setting the State property of the Entry object to EntityState.Modified, the system will recognize that the entity has been modified and persist the changes to the database accordingly.
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?
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 am trying to update the "ModifiedBy" field in a Sharepoint discussion board using the Client Object Model. By changing the "Editor" and "Author" fields, I can change the "ModifiedBy" that appears on the list view. However, once you click on a discussion post, the "ModifiedBy" field that appears there (the one with the picture above it) does not reflect the changes. After experimenting, I discovered that the field I need to change to correct this is called "MyEditor". Unfortunately, this field is read-only.
In the code below, I try to change the read-only settings of the field to false. When I look at the MyEditor field in Visual Studio's debugger after the ExecuteQuery() line at the bottom of the first block, it shows that the ReadOnlyField value has in fact been set to false.
sharepointContext.Load(discussionList);
sharepointContext.ExecuteQuery();
var fields = discussionList.Fields;
sharepointContext.Load(fields);
sharepointContext.ExecuteQuery();
var field = fields.GetByInternalNameOrTitle("MyEditor");
field.ReadOnlyField = false;
field.Update();
sharepointContext.Load(field);
sharepointContext.ExecuteQuery();
The code above executes with no problems. The problem comes with this next block:
//...Code to initialize discussionItem...
discussionItem["MyEditor"] = 0;
discussionItem["Editor"] = 0;
discussionItem["Author"] = 0;
discussionItem["Body"] = "Testing";
discussionItem["Title"] = "Hello Worlds";
discussionItem.Update();
sharepointContext.Load(discussionItem);
sharepointContext.ExecuteQuery();
When the code reaches the ExecuteQuery() at the bottom of the second block, it throws a ServerException with the following message:
Invalid data has been used to update the list item.
The field you are trying to update may be read only.
To make sure that the MyEditor field was the one causing the exception to be thrown, I commented out the line where I set it and ran the code again. Everything worked fine. I don't understand what is wrong, can someone help me?
In case someone needs to find the user by name, it goes like this:
private static FieldUserValue GetUser(ClientContext clientContext, string userName)
{
var userValue = new FieldUserValue();
var newUser = clientContext.Web.EnsureUser(userName);
clientContext.Load(newUser);
clientContext.ExecuteQuery();
userValue.LookupId = newUser.Id;
return userValue;
}
The returned value can be set via item["Author"]
ModifiedBy and CreadtedBy calculated automatically from Author and Editor you need to change only Author and Editor fields like this:
using (var clientContext = new ClientContext(#"http://server"))
{
var web = clientContext.Web;
var lst = web.Lists.GetByTitle("Discus");
var item = lst.GetItemById(2);
item["Author"] = 3;
item["Editor"] = 2;
item.Update();
clientContext.ExecuteQuery();
Console.WriteLine("done");
}
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?