I want to update multiple columns in Entity Framework. I now use this :
var user = new Relations { Id=1, Status = 1, Date = DateTime.Now, Notification = 0 };
db.Relations.Attach(user);
db.Entry(user).Property(x => x.Status).IsModified = true;
db.Entry(user).Property(x => x.Notification).IsModified = true;
db.Entry(user).Property(x => x.Date).IsModified = true;
db.Configuration.ValidateOnSaveEnabled = false;
db.SaveChanges();
Is there a better way to update columns without repeating the code db.Entry(user).Property several times ?
you can Use EntityState Like this:
var user=db.users.Find(userId);
user.name="new name";
user.age=txtAge.text;
user.address=txtAddress.text;
context.Entry(user).State=Entitystate.Modified;
I prefer use:
var existingUser = context.Set<User>().Where(u => u.Id == 1);
context.Entry(existingUser).CurrentValues.SetValues(user);
Or you can use a 3rd lib like GraphDiff.
Yo update an entity you don't need to do this:
// build your entity object with new values
var user = new Relations { Id=1, Status = 1, Date = DateTime.Now, Notification = 0 };
//attach as modified in one single step
db.Entry(user).State = EntityState.Modified;
//execute update
db.SaveChanges();
This assumes you are setting all entity fields and there isn't RowVersion field in your entity. Extra steps would be required to manage these other situations.
Try this,
using (var db = new YourDb())
{
try
{
db.Entry(user).State = EntityState.Modified;
}
catch (Exception)
{
return false;
}
db.SaveChanges();
return true;
}
When an item is fetched via the context it is
automatically tracked in that context unless you change the default behavior.
So you could simple do:
var txtInputAge = 18;
var txtAdrressLine1 = "Some cool place"
//fetch the user
var user = db.Users.Find(userId);
//change the properties
user.Name = "new cooler name";
user.Age = txtInputAge;
user.Address = txtAdrressLine1;
//call save changes
db.SaveChanges();
Update - Add would look like
//create new entry
User user = new User();
user.Name = "new cooler name";
user.Age = txtInputAge;
user.Address = txtAdrressLine1;
//add to context
db.Users.Add(user);
//call save changes
db.SaveChanges();
using (var dbcontext = new MyModel())
{
var matchedRecords = dbcontext.DummyTable.Where(e => e.code.Equals(entry.code) &&
e.isValid.Equals(true)).ToList();
matchedRecords.ForEach(e => e.isValid = false);
dbcontext.SaveChanges();
}
Related
So i want to update an entry's Valid to column, and then insert a new copy of it with a new value. The issue is it seems to skip the update statement, and just inserts a new copy of it.
foreach (Model data in Data)
{
var entry = context.table.Where(x=>x.id == data.id).FirstOrDefault();
entry.ValidTo = DateTime.Now;
ctx.Update(entry);
entry.id = 0;
entry.ValidTo = new DateTime(9999, 12, 31);
entry.ValidFrom = DateTime.Now;
entry.Value = adjustmentmodel.Value;
ctx.Add(entry);
}
ctx.SaveChanges();
I tried inserting a saveChanges after ctx.update(entry), and that works, but is pretty slow. So i wanted to hear if there was a way, to only have to save the changes at the end?
I am using dotnet 5 and EF core 5.0.17
Separate your entity references, there is no reason to re-use it.
foreach (Model data in Data)
{
// Update the entity
var entry = context.table.Where(x => x.id == data.id).FirstOrDefault();
entry.ValidTo = DateTime.Now;
// Add a new entry
ctx.Add(new Entry
{
// what you need for the new entry
});
}
// Save the changes within a single transaction
ctx.SaveChanges();
Please try using UpdateRange and AddRange method once.
var entry = Context.table.Where(x => Data.Select(y => y.id).Contains(x.id)).ToList();
entry = entry.ForEach(res =>
{
res.ValidTo = DateTime.Now
}).ToList();
ctx.UpdateRange(entry);
entry = entry.ForEach(res =>
{
res.ValidTo = new DateTime(9999, 12, 31);
res.ValidFrom = DateTime.Now;
res.Value = adjustmentmodel.Value;
}).ToList();
ctx.AddRange(entry);
ctx.SaveChanges();
I am trying to update one single field in a table but it's giving me an error saying that the other content is null. I'm trying to update one single field from a table and leave the other fields as they were.
Code so far:
var user = new User() { CardNumber = cardNumber };
using (var db = new Entities())
{
db.Users.Attach(user);
db.Entry(user).Property(x => x.CardNumber).IsModified = true;
db.Configuration.ValidateOnSaveEnabled = false;
db.SaveChanges();
}
Here is a code example to update the card number and save it.
using (var db = new Entities())
{
User user = db.Users.Where(u => u.Id == userIdToBeUpdated).FirstOrDefault();
user.CardNumber = cardNumber;
db.SaveChanges();
}
I have method in controller
It receive data from post request and write to table
Here is code
[ResponseType(typeof(TimeTable))]
public IHttpActionResult PostTimeTable(TimeTable timeTable)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (ModelState.IsValid)
{
DateTime dt = DateTime.Today;
TimeTable c = (from x in db.TimeTables
where x.Company == timeTable.Company && x.INN == timeTable.INN
select x).First();
c.StartPause = timeTable.StartPause;
c.StartDay = timeTable.StartDay;
c.EndPause = timeTable.EndPause;
c.EndDay = timeTable.EndDay;
db.SaveChanges();
}
db.TimeTables.Add(timeTable);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = timeTable.Id }, timeTable);
}
But it works well when record with INN and Company already in db.
But if it not in database I need to create new entry.
How I need to modify this method?
You can use a flag (exisingCompanyFlag) for edit mode or add new mode like this
bool existingCompanyFlag = true;
TimeTable c = (from x in db.TimeTables
where x.Company == timeTable.Company && x.INN == timeTable.INN
select x).FirstOrDefult();
if (c == null)
{
existingCompanyFlag = false;
c = new TimeTable();
}
c.StartPause = timeTable.StartPause;
c.StartDay = timeTable.StartDay;
c.EndPause = timeTable.EndPause;
c.EndDay = timeTable.EndDay;
if (!existingCompanyFlag)
db.TimeTables.Add(c);
You need a separate branch in your code for the insert case.
if (ModelState.IsValid) {
if (addingNewRow) {
TimeTable tt = new TimeTable {
// Populate properties (except identity columns)
};
db.TimeTables.Add(tt);
} else {
// update
}
db.SaveChanges();
}
To link to other entities use one of:
Assign instances:
x.Company = theCompany;
or, assign the instance id
x.CompanyId = companyId;
(#1 is easier if you already have the other entity loaded or are creating it – EF will sort out the ids – while #2 saves loading the whole other entity.)
public ActionResult Event_History(int id = 0)
{
//set into false the active flag of the event
Events_Info_tbl events = db.Events_Info_tbl.Find(id);
events.is_active = false;
db.Entry(events).State = EntityState.Modified;
//set the category under this event into inactive
List<Events_Category_tbl> category = new List<Events_Category_tbl>();
category = db.Events_Category_tbl.Where(x=>x.events_info_id==id).ToList();
foreach(var i in category){
Events_Category_tbl cat = new Events_Category_tbl();
cat.is_active = false;
db.Entry(cat).State = EntityState.Modified;
}
db.SaveChanges();
TempData["MessageAlert"] = "Event is save in history!";
return RedirectToAction("Index");
}
Iam planning to set into inactive all the category belongs to that particular event but when I try to run this code an error displayed "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key." pointing to this part of my code db.Entry(cat).State = EntityState.Modified;
foreach(var i in category){
Events_Category_tbl cat = new Events_Category_tbl();
cat.is_active = false;
db.Entry(cat).State = EntityState.Modified;
}
This part does not make any sense. You should not create a new instance of Events_Category_tbl.
You should instead just
foreach(var i in category){
i.is_active = false;
}
Below code try to create new object and save in DB, and all new object has same Id that's why give that error:
Events_Category_tbl cat = new Events_Category_tbl();
cat.is_active = false;
db.Entry(cat).State = EntityState.Modified;
You don't need to create new object, just update the retrieved entity:
public ActionResult Event_History(int id = 0)
{
//set into false the active flag of the event
var events = db.Events_Info_tbl.Find(id);
events.is_active = false;
//set the category under this event into inactive
var category = db.Events_Category_tbl.Where(x=>x.events_info_id==id).ToList();
foreach(var cat in category){
cat.is_active = false;
}
db.SaveChanges();
TempData["MessageAlert"] = "Event is save in history!";
return RedirectToAction("Index");
}
categories in a table may repeat themselves.... please replace:
db.Events_Category_tbl.Where(x=>x.events_info_id==id).ToList()
with
db.Events_Category_tbl.Where(x=>x.events_info_id==id).Distinct().ToList()
THAT WAY YOU WILL MAKE SURE THAT EVERY ITEM REPEAT ONLY ONCE
I'm trying to insert some data in my database using Entity Framework model, but for some unknown reasons to me, it does nothing.
Am I missing something here?
using (var context = new DatabaseEntities())
{
var t = new test
{
ID = Guid.NewGuid(),
name = "blah",
};
context.AddTotest(t);
context.SaveChanges();
}
It should be:
context.TableName.Add(TableEntityInstance);
For versions of entity framework before 6, it was:
context.TableName.AddObject(TableEntityInstance);
Where:
TableName: the name of the table in the database.
TableEntityInstance: an instance of the table entity class.
If your table is Orders, then:
Order order = new Order();
context.Orders.Add(order);
For example:
var id = Guid.NewGuid();
// insert
using (var db = new EfContext("name=EfSample"))
{
var customers = db.Set<Customer>();
customers.Add( new Customer { CustomerId = id, Name = "John Doe" } );
db.SaveChanges();
}
Here is an example:
public void UpdatePlayerScreen(byte[] imageBytes, string installationKey)
{
var player = (from p in this.ObjectContext.Players where p.InstallationKey == installationKey select p).FirstOrDefault();
var current = (from d in this.ObjectContext.Screenshots where d.PlayerID == player.ID select d).FirstOrDefault();
if (current != null)
{
current.Screen = imageBytes;
current.Refreshed = DateTime.Now;
this.ObjectContext.SaveChanges();
}
else
{
Screenshot screenshot = new Screenshot();
screenshot.ID = Guid.NewGuid();
screenshot.Interval = 1000;
screenshot.IsTurnedOn = true;
screenshot.PlayerID = player.ID;
screenshot.Refreshed = DateTime.Now;
screenshot.Screen = imageBytes;
this.ObjectContext.Screenshots.Add(screenshot);
this.ObjectContext.SaveChanges();
}
}
var context = new DatabaseEntities();
var t = new test //Make sure you have a table called test in DB
{
ID = Guid.NewGuid(),
name = "blah",
};
context.test.Add(t);
context.SaveChanges();
Should do it
[HttpPost] // it use when you write logic on button click event
public ActionResult DemoInsert(EmployeeModel emp)
{
Employee emptbl = new Employee(); // make object of table
emptbl.EmpName = emp.EmpName;
emptbl.EmpAddress = emp.EmpAddress; // add if any field you want insert
dbc.Employees.Add(emptbl); // pass the table object
dbc.SaveChanges();
return View();
}