UpdateOnSubmit from dbml? - c#

I have some generated classes representing a table from a dbml file
inserting a record in the table works fine with Name as a primary key
dbDataContext nc = new dbDataContext(connectionstring);
Action action = new Action();
action.Name = "1234"; // primary key
nc.Actions.InsertOnSubmit(action);
nc.SubmitChanges();
But how to update a record when Name already exists? There seems to be no UpdateOnSubmit or anything. There doesnt seem to be a clear answer on this.

First you need to get the record from database,and then do the update in that object and save the changes.
Action action = nc.Actions.FristOrDefault(e=>e.Name="1234");
if(action!=null)
{
action.SomeOtherProperty="NewValue";
}
nc.SubmitChanges();

Handle both the add and update cases
public void Persist(Company company)
{
var companyInDb = _dbSet.SingleOrDefault(c => c.Id == company.Id);
if (companyInDb != null)
{
_context.Entry(companyInDb).CurrentValues.SetValues(company);
}
else
{
_dbSet.Add(company);
}
_context.SaveChanges();
}

Related

Add or Update a Record?

I have an MVC application with the following code in the POST method of the controller. I am doing an EF Add and obviously that is not right. I want it to add the record if it doesn't exist, otherwise Update. How can I do that please?
try
{
AttributeEntities db = new AttributeEntities();
IEnumerable<string> items = viewModel.SelectedAttributes2;
int i = 0;
foreach (var item in items)
{
var temp = item;
// Save it
SelectedHarmonyAttribute attribute = new SelectedHarmonyAttribute();
attribute.CustomLabel = viewModel.ItemCaptionText;
attribute.IsVisible = viewModel.Isselected;
string harmonyAttributeID = item.Substring(1, 1);
// attribute.OrderNumber = Convert.ToInt32(order);
attribute.OrderNumber = i++;
attribute.HarmonyAttribute_ID = Convert.ToInt32(harmonyAttributeID);
db.SelectedHarmonyAttributes.Add(attribute);
db.SaveChanges();
}
}
You would need to check the database for the record you are trying to add/update. If the look-up returns null, that means that it doesn't exist in the database. If it does, you can modify the record that you looked up and call db.SaveChanges() to persist the changes you made to the database.
Edit:
int id = Convert.ToInt32(harmonyAttributeID);
var existingEntry = db.SelectedHarmonyAttributes.SingleOrDefault(x => x.HarmonyAttribute_ID == id);
One common way to determine an add or update is by simply looking at an identifier field, and setting the appropriate state.
using System.Data;
SelectedHarmonyAttribute attribute;
using (var db = new YourDbContext())
{
db.Entry(attribute).State = attribute.HarmonyAttribute_ID == 0 ? EntityState.Added : EntityState.Modified;
db.SaveChanges();
}
You could import the System.Data.Entity.Migrations namespace and use the AddOrUpdate extension method:
db.SelectedHarmonyAttributes.AddOrUpdate(attribute);
db.SaveChanges();
EDIT:
I'm assuming that SelectedHarmonyAttributes is of type DbSet
EDIT2:
Only drawback with doing it this way (and it may not be a concern for you), is that your entity isn't responsible for it's own state change. This means that you can update any property of the entity to something invalid, where you might want to internally validate it on the entity itself or maybe do some other processing you always want to occur on update. If these things are a concern for you, you should add a public Update method onto the entity and check for its existence on the database first. e.g:
var attribute = db.SelectedHarmonyAttributes.SingleOrDefault(x => x.HarmonyAttribute_ID == harmonyAttributeID);
if (attribute != null)
{
attribute.Update(viewModel.ItemCaptionText, viewModel.Isselected, i++);
}
else
{
attribute = new Attribute(viewModel.ItemCaptionText, viewModel.Isselected);
db.SelectedHarmonyAttributes.Add(attribute);
}
db.SaveChanges();
Your update method might look something like:
public void Update(string customLabel, bool isVisible, int orderNumber)
{
if (!MyValidationMethod())
{
throw new MyCustomException();
}
CustomLabel = customLabel;
IsVisible = isVisible;
OrderNumber = orderNumber;
PerformMyAdditionalProcessingThatIAlwaysWantToHappen();
}
Then make all of the entities' properties public "get" but protected "set" so they can't be updated from outside the entity itself. This might be going off an a bit of a tangent but using the AddOrUpdate method would assume you don't want to control the way an update occurs and protect your domain entity from getting into an invalid state etc. Hope this helps!

Enity Framework updating with a child table causing errors

I have the following update function
public void UpdateBatchDefinition(BatchDefinition batchToUpdate)
{
if (batchToUpdate == null)
{
throw new ArgumentNullException("batchToUpdate");
}
BatchDefinition foundDefinition =
this.context.BatchDefinitions.SingleOrDefault(definition => definition.Id == batchToUpdate.Id);
if (foundDefinition != null)
{
if (!string.IsNullOrWhiteSpace(batchToUpdate.Name))
{
foundDefinition.Name = batchToUpdate.Name;
}
if (!string.IsNullOrWhiteSpace(batchToUpdate.Description))
{
foundDefinition.Description = batchToUpdate.Description;
}
if (!string.IsNullOrWhiteSpace(batchToUpdate.LoadType))
{
foundDefinition.LoadType = batchToUpdate.LoadType;
}
if (batchToUpdate.JobId != Guid.Empty)
{
foundDefinition.JobId = batchToUpdate.JobId;
}
foundDefinition.Tables = batchToUpdate.Tables;
this.context.SaveChanges();
}
}
the issue I am having Is when I am trying to update the Tables list. Tables is a List of Table and Table is a Entity of another table
Tables could be added to, removed from or left alone. I need to update that with what ever is being passed in
when I run this right now I get an 'EntityValidationErrors' error, though it wont tell me what the validation issue actually is.
on Inserting I got the same error but was able to fix it using the following
var underlyingContext = this.context as DbContext;
if (underlyingContext != null)
{
foreach (var table in batchDefinition.Tables)
{
// Need to mark the table entity as unchanged or
// else EF will treat it as a new table
underlyingContext.Entry(table).State = EntityState.Unchanged;
}
}
so I tried using that in this update function
var underlyingContext = this.context as DbContext;
if (underlyingContext != null)
{
foreach (var table in foundDefinition.Tables)
{
// Need to mark the table entity as unchanged or
//else EF will treat it as a new table
underlyingContext.Entry(table).State = EntityState.Unchanged;
}
}
foundDefinition.Tables = batchToUpdate.Tables;
and I get the following error instead:
AcceptChanges cannot continue because the object's key values conflict
with another object in the ObjectStateManager. Make sure that the key
values are unique before calling AcceptChanges.
Any thoughts one what I am missing here?
Change end of your update method like this:
foreach (var t in foundDefinition.Tables.ToList())
Context.Tables.Remove(t);
foundDefinition.Tables = batchToUpdate.Tables;
this.context.SaveChanges();
And about your last error, it is said that there are some duplicates in your context. So, EF can't save the context changes into the db (because there are duplicates in the context!)
In fact, I don't know the last error is from add or delete - you didn't mention clearly. So, I don't know the last two code samples are from your add method, or your update method...
However for update, the trick I mentioned here, must solve your problem for update...

Error while adding a row and then updating a row using EF

Currently I am attempting to add a new row to a database table through AJAX which is working fine. But then I try to update a different table and I get an error. Here is my code and the error I am encountering.
Error
The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state.
Line 41: _db.ChampionCounters.Attach(champion);
Code
[HttpPost]
public ActionResult VoteYes(int id)
{
string results;
if (Request.IsAuthenticated)
{
var checkFirst =
from c in _db.UserCounterLinks
where c.counterId == id && c.userName == User.Identity.Name
select c;
if (checkFirst.Any())
{
results = "You have already voted on this counter.";
return Json(results);
}
var userVoteLink = new UserCounterLink { counterId = id, userName = User.Identity.Name, userAgree = true };
_db.UserCounterLinks.AddObject(userVoteLink);
var champion = _db.ChampionCounters.SingleOrDefault(c => c.id == id);
if (champion != null)
{
champion.positiveVotes++;
_db.ChampionCounters.Attach(champion);
}
_db.SaveChanges();
results = "Voted";
} else
{
results = "You must be logged in to vote.";
}
return Json(results);
}
Summary
The code above is from the controller that handles the Ajax post. Like I said the userVoteLink table creates a record just fine. But when I try to update the other table ChampionCounters the error is thrown.
Thanks in advance!
You don't need to attach the instance because the context is already tracking that instance. Just remove the _db.ChampionCounters.Attach(champion); line.

Save changes back to database using entity framework

I have simple query that loads data from two tables into GUI. I'm saving loaded data to widely available object Clients currentlySelectedClient.
using (var context = new EntityBazaCRM())
{
currentlySelectedClient = context.Kliencis.Include("Podmioty").FirstOrDefault(d => d.KlienciID == klientId);
if (currentlySelectedClient != null)
{
textImie.Text = currentlySelectedClient.Podmioty.PodmiotOsobaImie;
textNazwisko.Text = currentlySelectedClient.Podmioty.PodmiotOsobaNazwisko;
}
else
{
textNazwa.Text = currentlySelectedClient.Podmioty.PodmiotFirmaNazwa;
}
}
So now if I would like to:
1) Save changes made by user how do I do it? Will I have to prepare something on database side? How do I handle modifying multiple tables (some data goes here, some there)? My current code seems to write .KlienciHaslo just fine, but it doesn't affect Podmioty at all. I tried different combinations but no luck.
2) Add new client to database (and save information to related tables as well)?
currentClient.Podmioty.PodmiotOsobaImie = textImie.Text; // not saved
currentClient.Podmioty.PodmiotOsobaNazwisko = textNazwisko.Text; // not saved
currentClient.KlienciHaslo = "TEST111"; // saved
using (var context = new EntityBazaCRM())
{
var objectInDB = context.Kliencis.SingleOrDefault(t => t.KlienciID == currentClient.KlienciID);
if (objectInDB != null)
{
// context.ObjectStateManager.ChangeObjectState(currentClient.Podmioty, EntityState.Modified);
//context.Podmioties.Attach(currentClient.Podmioty);
context.Kliencis.ApplyCurrentValues(currentClient); // update current client
//context.ApplyCurrentValues("Podmioty", currentClient.Podmioty); // update current client
}
else
{
context.Kliencis.AddObject(currentClient); // save new Client
}
context.SaveChanges();
}
How can I achieve both?
Edit for an answer (doesn't save anything ):
currentClient.Podmioty.PodmiotOsobaImie = textImie.Text; // no save
currentClient.Podmioty.PodmiotOsobaNazwisko = textNazwisko.Text; // no save
currentClient.KlienciHaslo = "TEST1134"; // no save
using (var context = new EntityBazaCRM())
{
if (context.Kliencis.Any(t => t.KlienciID == currentClient.KlienciID))
{
context.Kliencis.Attach(currentClient); // update current client
}
else
{
context.Kliencis.AddObject(currentClient); // save new Client
}
context.SaveChanges();
}
Apparently ApplyCurrentValues only works with scalar properties.
If you attach the currentClient then associated objects should also attach, which means they'll be updated when you SaveChanges()
But you'll get an Object with the key exists exception because you are already loading the object from the database into the objectInDB variable. The context can only contain one copy of a Entity, and it knows that currentClient is the same as objectInDB so throws an exception.
Try this pattern instead
if (context.Kliencis.Any(t => t.KlienciID == currentClient.KlienciID))
{
context.Kliencis.Attach(currentClient); // update current client
}
else
{
context.Kliencis.AddObject(currentClient); // save new Client
}
or if you're using an identity as the ID, then
// if the ID is != 0 then it's an existing database record
if (currentClient.KlienciID != 0)
{
context.Kliencis.Attach(currentClient); // update current client
}
else // the ID is 0; it's a new record
{
context.Kliencis.AddObject(currentClient); // save new Client
}
After some work and help from Kirk about the ObjectStateManager error that I was getting I managed to fix this. This code allows me to save both changes to both tables.
currentClient.Podmioty.PodmiotOsobaImie = textImie.Text;
currentClient.Podmioty.PodmiotOsobaNazwisko = textNazwisko.Text;
currentClient.KlienciHaslo = "TEST1134";
using (var context = new EntityBazaCRM()) {
if (context.Kliencis.Any(t => t.KlienciID == currentClient.KlienciID)) {
context.Podmioties.Attach(currentClient.Podmioty);
context.Kliencis.Attach(currentClient);
context.ObjectStateManager.ChangeObjectState(currentClient.Podmioty, EntityState.Modified);
context.ObjectStateManager.ChangeObjectState(currentClient, EntityState.Modified);
} else {
context.Kliencis.AddObject(currentClient); // save new Client
}
context.SaveChanges();
}

How to Update with LINQ?

currently, I'm doing an update similar to as follows, because I can't see a better way of doing it. I've tried suggestions that I've read in blogs but none work, such as
http://msdn.microsoft.com/en-us/library/bb425822.aspx
and
http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx
Maybe these do work and I'm missing some point. Has anyone else had luck with them?
// please note this isn't the actual code.
// I've modified it to clarify the point I wanted to make
// and also I didn't want to post our code here!
public bool UpdateMyStuff(int myId, List<int> funds)
{
// get MyTypes that correspond to the ID I want to update
IQueryable<MyType> myTypes =
database.MyTypes.Where(xx => xx.MyType_MyId == myId);
// delete them from the database
foreach (db.MyType mt in myTypes)
{
database.MyTypes.DeleteOnSubmit(mt);
}
database.SubmitChanges();
// create a new row for each item I wanted to update, and insert it
foreach (int fund in funds)
{
database.MyType mt = new database.MyType
{
MyType_MyId = myId,
fund_id = fund
};
database.MyTypes.InsertOnSubmit(mt);
}
// try to commit the insert
try
{
database.SubmitChanges();
return true;
}
catch (Exception)
{
return false;
throw;
}
}
Unfortunately, there isn't a database.MyTypes.Update() method so I don't know a better way to do it. Can sombody suggest what I could do? Thanks.
..as a side note, why isn't there an Update() method?
Eh?
public void UpdateCustomer(int CustomerId, string CustomerName)
{
using (MyDataContext dc = new MyDataContext)
{
//retrieve an object from the datacontext.
// datacontext tracks changes to this instance!!!
Customer customer = dc.Customers.First(c => c.ID = CustomerId);
// property assignment is a change to this instance
customer.Name = CustomerName;
//dc knows that customer has changed
// and makes that change in the database
dc.SubmitChanges();
}
}

Categories