I want to update some of my columns value using entity framework
My code is as follows
public static void UpdateData(string contentMenu, int eid) //Update data in database
{
using (var context = new CmsContext())
{
try
{
var objDataContent = new Content
{
MenuContent = contentMenu,
ModifiedDateTime = DateTime.Now
};
//Code to update only MenuContent and ModifiedDateTime whose id=eid
GetRecords();
}
catch (Exception ex)
{
//
}
}
}
There are lot of answers in S/O but none of them helped me.
I followed https://stackoverflow.com/a/5567616/4701699
How can I update these two columns on the basis of id parameters like MSSQL query
update [CMS Menu].[dbo].[Contents] set MenuContent = 'testing' ,
ModifiedDateTime ='2016-01-02 16:02:15.803' where ContentId=2
You Can Update Your Column Entries by Using Linq:-
Here Are Example Code:-
var data = db.Content.FirstOrDefault(x=>x.ContentId==eID);
data.ModiFiedDateTime = DateTime.Now;
data.MenuContent = contentMenu;
db.SaveChanges();
Related
I have number of records that I have loaded from database and I want to update set couple values before I return them. The only main requirement I do not want multiple commands updating each record one by one.
Please note my ids are GUIDs(uniqueidentifier)
so far I have my code as
public IEnumerable<Person> GetUnprocessedPeople(int batchSize)
{
List<Queue_ImportQueue> list;
using (IDbConnection db = OpenedConnection)
{
string peopleList = $"SELECT TOP({batchSize}) * FROM [dbo].[Person]";
list = db.Query<Person>(peopleList).ToList();
using (IDbTransaction transactionScope = db.BeginTransaction(IsolationLevel.Serializable))
{
string updateQuery = $"UPDATE [dbo].[Person] SET Created = GETDATE() WHERE Id ='#ids'";
try
{
db.Execute(updateQuery, new { Id = list.Select(x => x.Id) }, transactionScope);
transactionScope.Commit();
}
catch (Exception ex)
{
transactionScope.Rollback();
throw;
}
}
}
return list;
}
OK the solution was quite simple.
There is no need for specific casting.
just ensure you have all arguments correct.
So extract that has fixed the query for me:
string updateQuery = $"UPDATE [dbo].[Person] SET Created = GETDATE() WHERE Id ='#Ids'";
...
db.Execute(updateQuery, new { Ids = list.Select(x => x.Id) }, transactionScope);
I'm trying to insert data into a MariaDB with EntityFrameWork 5 in Visual Studio. I created the database on the server itself and imported the model in Visual Studio. I'm using three tables and they are linked.
A draing table, project table and tag table.
Entities are: drawing (many---1) project (1---many) tag.
For the insert I use the code below. But it throws an DbUpdateEntityException who tells that he can't match the key between the drawing and project table because two or more primary keys are the same. I use a specific primary key for dat drawing which is definitely not the same with a other object in the table. The other primary keys are AUTO_INCREMENT So I guess that it tries to insert a new project but with the same project number which don't work but I don't really get it why it is doing this.
DateTime aktuellesDatum = DateTime.Now;
using (DMSContext db = new DMSContext())
{
foreach (ZeichnungInDB zeichnungInDB in zeichnungen)
{
zeichnungInDB.Volante_Index = getVolCountByDrawingNumber(zeichnungInDB.Zeichnungsnummer) + 1;
var zeichnung = new zeichnung()
{
Zeichnung_ID = zeichnungInDB.Dateiname + "_" + zeichnungInDB.Index + "_VOL_" + zeichnungInDB.Volante_Index + "_" + aktuellesDatum.ToShortDateString(),
Baugruppe = zeichnungInDB.Baugruppe,
Baugruppe_Hauptzeichnung = zeichnungInDB.Baugruppe_Hauptzeichnung,
Zeichnungsnummer = zeichnungInDB.Zeichnungsnummer,
Index = zeichnungInDB.Index,
Dateiname_Org = zeichnungInDB.Dateiname,
Aenderung_Ext = zeichnungInDB.Aenderung_Ext,
Aenderung_Int = "AE_" + zeichnungInDB.Projektnummer + aktuellesDatum,
Dokumententyp = zeichnungInDB.DokumentenTyp,
Dateiendung = zeichnungInDB.Extension,
Volante_Index = zeichnungInDB.Volante_Index,
MMS_Sachmerkmal = zeichnungInDB.Mms_Sachmerkmal,
Status = zeichnungInDB.Status,
Aenderung_Bemerkung_Txt = zeichnungInDB.Aenderung_Bemerkung_Text,
Einzel_Bemerkung_Txt = zeichnungInDB.Einzel_Bemerkung,
Ahang_Link = zeichnungInDB.Anhang_Link,
Einzel_Link = zeichnungInDB.Einzel_Link,
};
var projekt = new projekt()
{
Projektnummer = zeichnungInDB.Projektnummer,
};
var tag = new tag()
{
Tag1 = zeichnungInDB.Tag,
};
db.zeichnungs.Add(zeichnung);
db.projekts.Add(projekt);
db.tags.Add(tag);
}
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
// raise a new exception nesting
// the current instance as InnerException
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
}
maybe someone has an idea or a solution where the problem is.
(The "ZeichnungInDB" is an custom object and "zeichnungen" is ObservableCollection)
The other question I have is, I implemented a field for date time which is CURRENT_TIMESTSAMP but it only shows 0000-00-00 00:00:00 why is this?
Are you using fluent API? if you are, you should mark the id's properties as Identity like the example:
Property(p => p.DrawingId).
HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Or you can mark with an annotation in the primary key of your entities like the example:
public class drawing {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ind DrawingId {get; set;}
....
}
link:
http://www.opten.ch/blog/2014/03/5/configuring-entity-framework-with-fluent-api/
regards.
I wrote a very simple method. It saves data from class DayWeather to the database. Method checks if line with that day exist in table and update her or create a new line.
I am doing it by adding new class for LINQ and move table from Server Inspector to the constructor. It generate new class WeatherTBL.
Method itself looks like this:
public static void SaveDayWeather(DayWeather day)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var existingDay =
(from d in db.WeatherTBL
where d.DateTime.ToString() == day.Date.ToString()
select d).SingleOrDefault<WeatherTBL>();
if (existingDay != null)
{
existingDay.Temp = day.Temp;
existingDay.WindSpeed = day.WindSpeed;
existingDay.Pressure = day.Pressure;
existingDay.Humidity = day.Humidity;
existingDay.Cloudiness = day.Cloudiness;
existingDay.TypeRecip = day.TypeRecip;
db.SubmitChanges();
}
else
{
WeatherTBL newDay = new WeatherTBL();
newDay.DateTime = day.Date;
newDay.Temp = day.Temp;
newDay.WindSpeed = day.WindSpeed;
newDay.Pressure = day.Pressure;
newDay.Humidity = day.Humidity;
newDay.Cloudiness = day.Cloudiness;
newDay.TypeRecip = day.TypeRecip;
db.WeatherTBL.InsertOnSubmit(newDay);
db.SubmitChanges();
}
}
}
When I tried to call him from UnitTest project:
[TestMethod]
public void TestDataAccess()
{
DayWeather day = new DayWeather(DateTime.Now);
DataAccessClass.SaveDayWeather(day);
}
It write, that test has passed successfully. But if look into table, it has`t chanched.
No error messages shows. Does anyone know whats the problem?
P.S. Sorry for my bad English.
UDP
Problem was in that:
"...db maybe copied to the debug or release folder at every build, overwriting your modified one". Thanks #Silvermind
I wrote simple method to save employee details into Database.
private void AddNewEmployee()
{
using (DataContext objDataContext = new DataContext())
{
Employee objEmp = new Employee();
// fields to be insert
objEmp.EmployeeName = "John";
objEmp.EmployeeAge = 21;
objEmp.EmployeeDesc = "Designer";
objEmp.EmployeeAddress = "Northampton";
objDataContext.Employees.InsertOnSubmit(objEmp);
// executes the commands to implement the changes to the database
objDataContext.SubmitChanges();
}
}
Please try with lambda expression. In your code, var existingDay is of type IQueryable
In order to insert or update, you need a variable var existingDay of WeatherTBL type.
Hence try using below..
var existingDay =
db.WeatherTBL.SingleOrDefault(d => d.DateTime.Equals(day.Date.ToString()));
if(existingDay != null)
{
//so on...
}
Hope it should work..
Linq to SQL
Detail tc = new Detail();
tc.Name = txtName.Text;
tc.Contact = "92"+txtMobile.Text;
tc.Segment = txtSegment.Text;
var datetime = DateTime.Now;
tc.Datetime = datetime;
tc.RaisedBy = Global.Username;
dc.Details.InsertOnSubmit(tc);
try
{
dc.SubmitChanges();
MessageBox.Show("Record inserted successfully!");
txtName.Text = "";
txtSegment.Text = "";
txtMobile.Text = "";
}
catch (Exception ex)
{
MessageBox.Show("Record inserted Failed!");
}
Using LINQ to SQL in WCF I have a update record methods which ATM I manually assign each updated property.
Eg.
public void UpdateMachineRecord(Guid SessionID, int MachineRecordID, MachineRecord machineRecord)
{
if (!ValidSession(SessionID))
return;
using (MMHLINQSQLDataContext database = new MMHLINQSQLDataContext())
{
MachineRecord record = database.MachineRecords.Single(mr => mr.Job.OperationID == MachineRecordID);
record.ChangedBy = UserSession(SessionID).Name;
record.ChangedDate = DateTime.Now.ToString();
record.Date = machineRecord.Date;
record.EDI = machineRecord.EDI;
...
database.SubmitChanges();
}
}
My questions is: Is there a way to update the record using an entire entity?
Eg.
public void UpdateMachineRecord(Guid SessionID, int MachineRecordID, MachineRecord machineRecord)
{
if (!ValidSession(SessionID))
return;
using (MMHLINQSQLDataContext database = new MMHLINQSQLDataContext())
{
MachineRecord record = database.MachineRecords.Single(mr => mr.Job.OperationID == MachineRecordID);
record = machineRecord;
database.SubmitChanges();
}
}
You can do this.
database.MachineRecords.Attach(machineRecord, true);
database.SubmitChanges();
This will attach it as a modified entity (that's what the boolean parameter is for)
I'm having some issues in updating and inserting records using ASP.NET MVC and Entity Framework.
I have a form (which is a report) that is dynamically created and can have any amount of questions. I'm trying to allow the user to edit the report and submit the changes so that it is updated in the database.
I am retrieving the report to be edited from the database via a repository then setting it to an instance of ModeratorReport. I'm then changing the value of the properties and using db.SaveChanges to save the changes to the database.
The problem is that it is not saving the changes.
Please could someone advise me on what I am doing wrong?
Here is the Edit Action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(FormCollection formCollection, int moderatorReportId, string status)
{
ModeratorReport reportToEdit = repository.GetModeratorReportById(moderatorReportId);
List<QuestionAnswer> originalReportAnswers = repository.GetAllModeratorReportAnswers(moderatorReportId, status).ToList();
foreach (QuestionAnswer answer in originalReportAnswers) {
reportToEdit.QuestionAnswers.Remove(answer);
}
int sectionID;
int questionID;
foreach (string key in formCollection.AllKeys)
{
var value = formCollection[key.ToString()];
Match m = Regex.Match(key, "section(\\d+)_question(\\d+)");
if (m.Success) {
QuestionAnswer newAnswer = new QuestionAnswer();
sectionID = Convert.ToInt16(m.Groups[1].Value.ToString());
questionID = Convert.ToInt16(m.Groups[2].Value.ToString());
newAnswer.ModeratorReportID = moderatorReportId;
newAnswer.SectionID = sectionID;
newAnswer.QuestionID = questionID;
newAnswer.Answer = value;
newAnswer.Status = "SAVED";
reportToEdit.QuestionAnswers.Add(newAnswer);
}
}
reportToEdit.Status = "SAVED";
AuditItem auditItem = new AuditItem();
auditItem.ModeratorReportID = moderatorReportId;
auditItem.Status = "SAVED";
auditItem.AuditDate = DateTime.Now;
auditItem.Description = "The Moderator report..."
auditItem.UserID = User.Identity.Name;
reportToEdit.Audit.Add(auditItem);
db.SaveChanges();
return RedirectToAction("Details", new { id = moderatorReportId });
}
The problem looks like you're just not setting reportToEdit's EntityState to modified. Like so:
reportToEdit.Audit.Add(auditItem);
reportToEdit.EntityState = EntityState.Modified;
db.SaveChanges();
For more information about the EntityState enumeration, see this MSDN article.