DbUpdateException was unhandle by user code - entity-framework

I have such code in controller:
public string UpdateDapAnColumnSelected(int bode, int cauhoi, int selected, int userId)
{
MessageBox.Show(bode + " " + cauhoi + ", dap an: " + selected + "user Id: " + userId);
//add to database THi
THI updateThi = new THI();
updateThi.MABODE = bode;
updateThi.MACAUHOI = cauhoi;
updateThi.MADAPAN = selected;
updateThi.USERID = userId;
if (ModelState.IsValid)
{
db.THIs.Add(updateThi);
db.SaveChanges();
return "a";
}
return "a";
}
In the model context I have:
public virtual DbSet<THI> THIs { get; set; }
Class THI in Model:
public partial class THI
{
public int USERID { get; set; }
public int MABODE { get; set; }
public int MACAUHOI { get; set; }
public int MADAPAN { get; set; }
}
I can't save updateThi to database. Can you help me?
Thank you very much!

You published only partial class of THI, so it's difficult to deduce is Id of THI class unique.
This exception is often caused by attemption to add duplicated primary key. You should have Id or THIID property to follow EF conventions. Thanks to that PK will be configured as an identity column.
Let me know does it work.
===EDIT===
And what is more - you're using Add method to update entity. You shouldn't, because then Id for sure will not be unique. EF will try to add the same record with identical Id into the database once again. Simply update properties and call SaveChanges, without Add() method.

Related

What is the proper way of updating navigation properties in EF Core?

In my EF Core solution I have the following model:
public class Deal
{
public string Id { get; set; }
public ResponsiblePerson ResponsiblePerson1 { get; set; }
public ResponsiblePerson ResponsiblePerson2 { get; set; }
public ResponsiblePerson ResponsiblePerson3 { get; set; }
}
public class ResponsiblePerson
{
public string Id { get; set; }
public string Name { get; set; }
}
When I am trying to update Deal navigations properties:
private void UpdateResponsiblePersons(string dealId, string person1Id, string person2Id, string person3Id)
{
var existingdeal = _dbContext.Deals
.Include(d => d.ResponsiblePerson1)
.Include(d => d.ResponsiblePerson2)
.Include(d => d.ResponsiblePerson3)
.Single(d => d.Id == dealId);
existingDeal.ResponsiblePerson1 = new ResponsiblePerson { Id = person1Id };
existingDeal.ResponsiblePerson2 = new ResponsiblePerson { Id = person2Id };
existingDeal.ResponsiblePerson3 = new ResponsiblePerson { Id = person3Id };
_dbContext.Entry(deal.ResponsiblePerson1).State = EntityState.Unchanged;
_dbContext.Entry(deal.ResponsiblePerson3).State = EntityState.Unchanged;
_dbContext.Entry(deal.ResponsiblePerson3).State = EntityState.Unchanged;
_dbContext.SaveChanges();
}
EF often fails with
System.InvalidOperationException: The instance of entity type 'ResponsiblePerson' cannot be tracked because another instance with the key value '{Id: 1}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
That is because sometimes existingdeal already contains the link to ResponsiblePerson with one of provided IDs in either ResponsiblePerson1 of ResponsiblePerson2 or ResponsiblePerson3 Navigation properties.
I know that one of possible solutions will be first to get ResponsiblePersons used for update from dbContext like
existingDeal.ResponsiblePerson1 = _dbContext.ResponsiblePersons.Find(person1Id)
But that means extra DB roundtrips.
Another solution is to expose foreign keys instead of navigation properties but it would make Deal model quite ugly.
Please advice me what is the best way of updating such references?

.Update() returns "Cannot update identity column"

There is a link on an Index-type display that directs control to the method below. The Voucher Status is updated to "Reconciled" then a save is attempted.
Everything appears to execute as it should until the Update/Save when I get the exception, "Cannot update identity column."
There are no navigation properties in the Voucher model. Both Identity columns are populated nicely on insert.
The model is here:
public class Voucher
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string VoucherId { get; set; }
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int64 VoucherNumber { get; set; }
[Required]
public string StudentId { get; set; }
public string FullName { get; set; }
[Required]
public string VoucherType { get; set; }
[Required]
public DateTime VoucherCreateDate { get; set; }
[Required]
public string VoucherStatus { get; set; }
}
public ViewResult ReconcileVoucher(string id) //, Voucher voucher)
{
Voucher voucher = _context.Vouchers
.Single(m => m.VoucherId == id);
if (id != voucher.VoucherId)
{
ModelState.AddModelError("InputStatus", "Indicated Voucher is not present " + voucher.FullName);
return View();
}
voucher.VoucherStatus = "Reconciled";
if (ModelState.IsValid)
{
try
{
_context.Update(voucher);
_context.SaveChanges();
ModelState.AddModelError("InputStatus", "Voucher was Reconciled for " + voucher.FullName);
}
catch (DbUpdateConcurrencyException ex)
{
CreateLogRow("Reconcile Voucher", "testUser", "Concurrency exception for " + voucher.StudentId, ex.Message);
if (!VoucherExists(voucher.VoucherId))
{
ModelState.AddModelError("InputStatus", "The Voucher for " + voucher.FullName + " cannot be found");
return View();
}
else
{
throw;
}
}
CreateLogRow("Reconcile Voucher", "testUser", "Voucher was edited for " + voucher.StudentId + " - " + voucher.FullName, null);
return View();
}
return View(voucher);
}
When you fetch an entity from the DbContext within the call and update property, you should not call Update, but rather just call SaveChanges.
I.e.
Voucher voucher = _context.Vouchers
.Single(m => m.VoucherId == id);
// ...
voucher.VoucherStatus = "Reconciled";
// ...
_context.SaveChanges();
Update will generate a statement that will update all columns on an entity, and while that should exclude columns that are marked as DatabaseGeneratedOption.Identity this may not be the case here. By letting the change tracking do its thing without the Update call, EF will generate an UPDATE statement for just the column(s) that changed.
Update would be more applicable when accepting an entity (as you had commented out) and attaching/updating its state as a whole. I don't recommend this approach as it overwrites all values and is vulnerable to a number of issues including stale data updates plus unexpected tampering from the client. (Modifying columns your UI does not allow by man-in-the-browser/middle attacks) It is better to load the entity fresh, validate incoming data, check row versions/modified timestamps for stale updates, etc. rather than accepting an entity at face value and pushing it onto the DB.
Edit: If these IDs are GUIDs in the DB, then why not cast them as GUIDs in the entity?
You're marking all the properties as modified by calling
_context.Update(voucher);
Either omit this call and let the change tracker determine the updated columns, or explicitly mark the VoucherNumber property as unmodified.
db.Update(voucher);
db.Entry(voucher).Property(nameof(Voucher.VoucherNumber)).IsModified = false;

Add/Update list in database using Entity framework 6

I have three tables QuestionBank,Question and Answer. " QuestionBank " will have list of Question and " Question " will have list of " Answer ".
QUESTIONBANK :-
public class QuestionBank
{
public int id { get; set; }
public string Text { get; set; }
public string Chapter { get; set; }
public string Standard { get; set; }
public List<Question> Question { get; set; }
public QuestionBank()
{
this.Question = new List<Question>();
}
}
QUESTION :-
public class Question
{
public int id { get; set; }
public string Title { get; set; }
public string QuestionText { get; set; }
public List<Answer> Answer { get; set; }
public string CorrectAnswer { get; set; }
public Question()
{
this.Answer = new List<Answer>();
}
}
ANSWER :-
public class Answer
{
public int id { get; set; }
public string AnswerText { get; set; }
}
WEB API :- //Edited
private IRepository<QuestionBank> _QuestionBankRepository;
public QuestionController(IRepository<QuestionBank> QuestionBankRepository)
{
_QuestionBankRepository = QuestionBankRepository;
}
[HttpPost]
[Route("Ques/Add")]
public Boolean Add(QuestionBank AddQuetionBankData)
{
var isQuetionBankPresent = _QuestionBankRepository.GetAll(p => p.Text == AddQuetionBankData.Text && p.Standard == AddQuetionBankData.Standard && p.Chapter == AddQuetionBankData.Chapter).FirstOrDefault<QuestionBank>();
if (isQuetionBankPresent != null)
{
/* Add the data in Question and Answer tables */
return false;
}
else
{
/* Add the data in all three tables */
return true;
}
}
I have this database for the web api. Now I want to add the data in database through json { "QuestionBank": QuestionBank, "Question": Question, "Answer": Answer } if the row is present in QuestionBank i dont want to add that data in QuestionBank table and only add the data in Question and Answer table with respective foreign keys. I am using the entity frame work and mvc 5 web api. I am stuck at this point. Please if any thing is needed let me know. Thanks in advance.
The Entity Framework way to update is to to Context.Entry([your object]).State = System.Data.Entity.EntityState.Modified; providing that the object is of the right type.
public Boolean Add(QuestionBank AddQuetionBankData)
{
bool flag = false;
var question = this.MapToQuestion(AddQuetionBankData); //map the input to the EF Type Question
var anwer = this.MapToAnswer(AddQuetionBankData); //map the input to the EF Type Answer
var isQuetionBankPresent = _QuestionBankRepository.GetAll(p => p.Text == AddQuetionBankData.Text && p.Standard == AddQuetionBankData.Standard && p.Chapter == AddQuetionBankData.Chapter).FirstOrDefault<QuestionBank>();
if (isQuetionBankPresent != null)
{
_context.Entry(question).State = EntityState.Modified;
_context.Entry(answer).State = EntityState.Modified;
/* Add the data in Question and Answer tables */
flag = false;
}
else
{
_context.Entry(question).State = EntityState.Modified;
_context.Entry(answer).State = EntityState.Modified;
_context.Entry(AddQuetionBankData).State = EntityState.Modified;
/* Add the data in all three tables */
flag = true;
}
_context.SaveChanges();
return flag;
}
private Question MapTo Question(QuestionBank q) //do this for Answers too
{
var _q = _context.Question.Where(a=>a.Id == q.Id).SingleOrDefault();
if(_q!=null)
{
_q.id = q.id; //this is already true
_q.Title = q.Title;
_q.QuestionText = q.Standard; //I guess
}
return _q;
}
The EF updates the Entity (the class you pass to the method Entry()) accordingly to its Type.
Notice that the position of the SaveChanges(): it works like a stored procedure, you do all the updates and the SaveChanges() is like the SQL COMMIT command.
You should also wrap the SaveChanges in a try/catch to handle errors, and dispose the _context.
EDIT
This class has as dependency IRepository<Question>, IRepository<QuestionBank>, and IRepository<Answer>.
You should create an UpdateController(or PublishController or whatever) that gets the three dependencies in the constructor (better a Facade Service), and call the Add() method for each one of them.
If you access directly the raw Database object you could do like I did and use the Entry() method for each table.

Improve navigation property names when reverse engineering a database

I'm using Entity Framework 5 with Visual Studio with Entity Framework Power Tools Beta 2 to reverse engineer moderately sized databases (~100 tables).
Unfortunately, the navigation properties do not have meaningful names. For example, if there are two tables:
CREATE TABLE Contacts (
ContactID INT IDENTITY (1, 1) NOT NULL,
...
CONSTRAINT PK_Contacts PRIMARY KEY CLUSTERED (ContactID ASC)
}
CREATE TABLE Projects (
ProjectID INT IDENTITY (1, 1) NOT NULL,
TechnicalContactID INT NOT NULL,
SalesContactID INT NOT NULL,
...
CONSTRAINT PK_Projects PRIMARY KEY CLUSTERED (ProjectID ASC),
CONSTRAINT FK_Projects_TechnicalContact FOREIGN KEY (TechnicalContactID)
REFERENCES Contacts (ContactID),
CONSTRAINT FK_Projects_SalesContact FOREIGN KEY (SalesContactID)
REFERENCES Contacts (ContactID),
...
}
This will generate classes like this:
public class Contact
{
public Contact()
{
this.Projects = new List<Project>();
this.Projects1 = new List<Project>();
}
public int ContactID { get; set; }
// ...
public virtual ICollection<Project> Projects { get; set; }
public virtual ICollection<Project> Projects1 { get; set; }
}
public class Project
{
public Project()
{
}
public int ProjectID { get; set; }
public int TechnicalContactID { get; set; }
public int SalesContactID { get; set; }
// ...
public virtual Contact Contact { get; set; }
public virtual Contact Contact1 { get; set; }
}
I see several variants which would all be better than this:
Use the name of the foreign key: For example, everything after the last underscore (FK_Projects_TechnicalContact --> TechnicalContact). Though this probably would be the solution with the most control, this may be more difficult to integrate with the existing templates.
Use the property name corresponding to the foreign key column: Strip off the suffix ID (TechnicalContactID --> TechnicalContact)
Use the concatenation of property name and the existing solution: Example TechnicalContactIDProjects (collection) and TechnicalContactIDContact
Luckily, it is possible to modify the templates by including them in the project.
The modifications would have to be made to Entity.tt and Mapping.tt. I find it difficult due to the lack of intellisense and debug possibilities to make those changes.
Concatenating property names (third in above list) is probably the easiest solution to implement.
How to change the creation of navigational properties in Entity.tt and Mapping.tt to achieve the following result:
public class Contact
{
public Contact()
{
this.TechnicalContactIDProjects = new List<Project>();
this.SalesContactIDProjects = new List<Project>();
}
public int ContactID { get; set; }
// ...
public virtual ICollection<Project> TechnicalContactIDProjects { get; set; }
public virtual ICollection<Project> SalesContactIDProjects { get; set; }
}
public class Project
{
public Project()
{
}
public int ProjectID { get; set; }
public int TechnicalContactID { get; set; }
public int SalesContactID { get; set; }
// ...
public virtual Contact TechnicalContactIDContact { get; set; }
public virtual Contact SalesContactIDContact { get; set; }
}
There a few things you need to change inside the .tt file. I choose to use the third solution you suggested but this requires to be formatted like FK_CollectionName_RelationName. I split them up with '_' and use the last string in the array.
I use the RelationName with the ToEndMember property to create a property name. FK_Projects_TechnicalContact will result in
//Plularized because of EF.
public virtual Contacts TechnicalContactContacts { get; set; }
and your projects will be like this.
public virtual ICollection<Projects> SalesContactProjects { get; set; }
public virtual ICollection<Projects> TechnicalContactProjects { get; set; }
Now the code you may ask. Ive added 2 functions to the CodeStringGenerator class in the T4 file. One which builds the propertyName recieving a NavigationProperty. and the other one generating the code for the property recieving a NavigationProperty and the name for the property.
//CodeStringGenerator class
public string GetPropertyNameForNavigationProperty(NavigationProperty navigationProperty)
{
var ForeignKeyName = navigationProperty.RelationshipType.Name.Split('_');
var propertyName = ForeignKeyName[ForeignKeyName.Length-1] + navigationProperty.ToEndMember.Name;
return propertyName;
}
public string NavigationProperty(NavigationProperty navigationProperty, string name)
{
var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType());
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1} {2} {{ {3}get; {4}set; }}",
AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)),
navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
name,
_code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
_code.SpaceAfter(Accessibility.ForSetter(navigationProperty)));
}
If you place the above code in the class you still need to change 2 parts. You need to find the place where the constructor part and the navigation property part are being build up of the entity. In the constructor part (around line 60) you need to replace the existing code by calling the method GetPropertyNameForNavigationProperty and passing this into the escape method.
var propName = codeStringGenerator.GetPropertyNameForNavigationProperty(navigationProperty);
#>
this.<#=code.Escape(propName)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>();
<#
And in the NavigationProperties part (around line 100) you also need to replace the code with the following.
var propName = codeStringGenerator.GetPropertyNameForNavigationProperty(navigationProperty);
#>
<#=codeStringGenerator.NavigationProperty(navigationProperty, propName)#>
<#
I hope this helps and you can always debug the GetPropertyNameForNavigationProperty function and play a little with the naming of the property.
Building on BikeMrown's answer, we can add Intellisense to the properties using the RelationshipName that is set in MSSQL:
Edit model.tt in your VS Project, and change this:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
<#
}
#>
<#=codeStringGenerator.NavigationProperty(navigationProperty)#>
<#
}
}
to this:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
<#
}
#>
/// <summary>
/// RelationshipName: <#=code.Escape(navigationProperty.RelationshipType.Name)#>
/// </summary>
<#=codeStringGenerator.NavigationProperty(navigationProperty)#>
<#
}
}
Now when you start typing a property name, you get a tooltip like this:
It's probably worth noting that if you change your DB model, the properties may find themselves pointing at different DB fields because the EF generates navigation property names based on their respective DB field name's alphabetic precedence!
Found this question/answer very helpful. However, I didn't want to do as much as Rikko's answer. I just needed to find the column name involved in the NavigationProperty and wasn't seeing how to get that in any of the samples (at least not without an edmx to pull from).
<#
var association = (AssociationType)navProperty.RelationshipType;
#> // <#= association.ReferentialConstraints.Single().ToProperties.Single().Name #>
The selected answer is awesome and got me going in the right direction for sure. But my big problem with it is that it took all of my already working navigation properties and appended the base type name to them, so you'd end up with with things like the following.
public virtual Need UnitNeed { get; set;}
public virtual ShiftEntered UnitShiftEntered {get; set;}`
So I dug into the proposed additions to the .tt file and modified them a bit to remove duplicate type naming and clean things up a bit. I figure there's gotta be someone else out there that would want the same thing so I figured I'd post my resolution here.
Here's the code to update within the public class CodeStringGenerator
public string GetPropertyNameForNavigationProperty(NavigationProperty navigationProperty, string entityname = "")
{
var ForeignKeyName = navigationProperty.RelationshipType.Name.Split('_');
var propertyName = "";
if (ForeignKeyName[ForeignKeyName.Length-1] != entityname){
var prepender = (ForeignKeyName[ForeignKeyName.Length-1].EndsWith(entityname)) ? ReplaceLastOccurrence(ForeignKeyName[ForeignKeyName.Length-1], entityname, "") : ForeignKeyName[ForeignKeyName.Length-1];
propertyName = prepender + navigationProperty.ToEndMember.Name;
}
else {
propertyName = navigationProperty.ToEndMember.Name;
}
return propertyName;
}
public string NavigationProperty(NavigationProperty navigationProperty, string name)
{
var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType());
var truname = name;
if(navigationProperty.ToEndMember.RelationshipMultiplicity != RelationshipMultiplicity.Many){
if(name.Split(endType.ToArray<char>()).Length > 1){
truname = ReplaceLastOccurrence(name, endType, "");
}
}
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1} {2} {{ {3}get; {4}set; }}",
AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)),
navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
truname,
_code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
_code.SpaceAfter(Accessibility.ForSetter(navigationProperty)));
}
public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
int place = Source.LastIndexOf(Find);
if(place == -1)
return Source;
string result = Source.Remove(place, Find.Length).Insert(place, Replace);
return result;
}
and here's the code to update within the model generation,
update both occurrences of this:
var propName = codeStringGenerator.GetPropertyNameForNavigationProperty(navigationProperty)
to this
var propName = codeStringGenerator.GetPropertyNameForNavigationProperty(navigationProperty, entity.Name);

Update in Entity Framework

I am using Entity Framework 5 in my project and I want to update a record. How do I do this?
Here is my base class.
using System;
namespace EF_Sample09.DomainClasses
{
public abstract class BaseEntity
{
public int Id { get; set; }
public DateTime CreatedOn { set; get; }
public string CreatedBy { set; get; }
public DateTime ModifiedOn { set; get; }
public string ModifiedBy { set; get; }
}
}
Taking from the great ADO.NET Entity Framework Overview:
using(AdventureWorksDB aw = new
AdventureWorksDB(Settings.Default.AdventureWorks)) {
// find all people hired at least 5 years ago
Query<SalesPerson> oldSalesPeople = aw.GetQuery<SalesPerson>(
"SELECT VALUE sp " +
"FROM AdventureWorks.AdventureWorksDB.SalesPeople AS sp " +
"WHERE sp.HireDate < #date",
new QueryParameter("#date", DateTime.Today.AddYears(-5)));
foreach(SalesPerson p in oldSalesPeople) {
// call the HR system through a webservice to see if this
// sales person has a promotion coming (note that this
// entity type is XML-serializable)
if(HRWebService.ReadyForPromotion(p)) {
p.Bonus += 10; // give a raise of 10% in the bonus
p.Title = "Senior Sales Representative"; // give a promotion
}
}
// push changes back to the database
aw.SaveChanges();
}
You basically just have to:
create your ObjectContext (or DbContext)
fetch some records
modify the objects
call the context's .SaveChanges() method to write those changes back to the database
That's it!