I am new to entity framework and right now struggling with an issue. I am using MVC api and EF6.
I was saving member details in a PUT method. That worked fine.
Now, I modified the code to save a comment (Added new method PublishComment()) as well but this breaks the code without any error message!! The debug session just hungs on the db.SaveChanges().
public void Put(Guid id, MemberListItem item)
{
using (Context db = new Context())
{
Person updPerson = db.People.Find(item.PersonID);
if (updPerson.PrincipleContact != item.PrincipalMember)
{
updPerson.PrincipleContact = item.PrincipalMember;
}
string memberName = updPerson.GivenName1;
Guid memberID = updPerson.MemberID;
db.Entry(updPerson).State = System.Data.Entity.EntityState.Modified;
PublishComment(db, memberID, "User Modified. " + memberName + " modified from user profile.");
db.SaveChanges();
}
public void PublishComment(Context db, Guid memberID, string comment)
{
MemberComment newComment = new MemberComment();
newComment.CommentID = new Guid();
newComment.MemberID = memberID;
newComment.DateAdded = DateTime.Now;
newComment.Comment = DateTime.Now.ToShortDateString() +": " + comment;
db.MemberComments.Add(newComment);
}
I think your issue is here:
newComment.CommentID = new Guid(); // eg {00000000-0000-0000-0000-000000000000}
But I'm not too sure why you are not seeing a duplicate key exception (which is what this looks like it would generate)
see Guid is all 0's (zeros)?
Related
When I update my member, I want to update his BankCheck too.
This is my database:
My bankCheck can be added, updated or deleted.
My member can be updated only (name, surname...)
I choose my member in my datagrid, and select Edit, my wpf app switch to an other page and display my member with Textbox etc.
I click on my button to add/edit/delete his bankCheck and I can edit the first bankCheck.
I delete the last bankCheck and I add an other (for example).
I press OK and I click on "Valid my Edit".
My program re-creates a new Member with his bankCheck and i made this:
private void EditMember(Member updatedMember)
{
try
{
using (var context = new KravMagaEntities())
{
context.Member.Attach(updatedMember);
context.Entry(updatedMember).State = EntityState.Modified;
context.SaveChanges();
}
ResetAllControls();
States.EnumToText(States.StatesEnum.UpdatingSuccess);
Application.Current.Dispatcher.Invoke(() =>
{
_managementService.IsVisibleAddTab(true);
_managementService.IsVisibleEditTab(false);
});
}
catch (Exception exception)
{
States.EnumToText(States.StatesEnum.Error, exception);
}
}
But I have this error:
A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
I don't know how I can fix this error.
Thank you.
My code:
private void OnEditMemberBtnClicked(object sender, RoutedEventArgs e)
{
try
{
var isValidateCertificat = IsValidDate(BirthDateTxt);
var isValidateBirth = IsValidDate(CertificateDateTxt);
var isValidateAutorisation = IsValidDate(AutorizationDateTxt);
var isValidateReglement = IsValidDate(RuleDateTxt);
if (isValidateBirth && isValidateCertificat && isValidateAutorisation && isValidateReglement)
{
States.EnumToText(States.StatesEnum.Updating);
var typePaiement = BankCheckRadio.IsChecked.Value;
var typePaiementText = typePaiement ? "Chèque" : "Espèce";
var doctor = "";
var dateCertificate = "";
if (BankCheckRadio.IsChecked.Value)
{
doctor = DoctorTxt.Text;
dateCertificate = CertificateDateTxt.Text;
}
var editedMember = new Member
{
id_Member = _idForEdit,
name_Member = UppercaseChar(NameTxt.Text),
surname_Member = UppercaseChar(SurnameTxt.Text),
birthDate_Member = BirthDateTxt.Text,
autorizationDate_Member = AutorizationDateTxt.Text,
address_Member = UppercaseChar(AddressTxt.Text),
postalCode_Member = PostalCodeTxt.Text,
country_Member = UppercaseChar(CountryTxt.Text),
fixPhone_Member = FixPhoneTxt.Text,
mobilePhone_Member = MobilePhoneTxt.Text,
mail_Member = MailTxt.Text,
beginDate_Member = BeginDateCombo.Text,
ruleDate_Member = RuleDateTxt.Text,
subscription_Member = SubscriptionCombo.Text,
typePaiement_Member = typePaiement,
typePaiementText_Member = typePaiementText,
federationNumero_Member = FederationNumeroTxt.Text.ToUpper(),
level_Member = LevelCombo.Text,
certificate_Member = CertificateCheckbox.IsChecked.Value,
doctor_Member = UppercaseChar(doctor),
certificateDate_Member = dateCertificate,
problem_Member = UppercaseChar(ProblemTxt.Text, true),
emergencyName_Member = UppercaseChar(EmergencyNameTxt.Text),
emergencyPhone_Member = EmergencyPhoneTxt.Text,
BankCheck = _bankChecks
};
if (_bankChecks != null)
{
using (var context = new KravMagaEntities())
{
foreach (var bankCheck in _bankChecks)
{
bankCheck.idMember_BankCheck = editedMember.id_Member;
context.Entry(bankCheck).State = EntityState.Added;
}
context.SaveChanges();
}
}
new Task(() => EditMember(editedMember)).Start();
}
}
catch (Exception exception)
{
States.EnumToText(States.StatesEnum.Error, exception);
}
}
So as I see, you're updating only Member, not all the modified BankAccounts. You're updating navigation property of entities from both sides but calling SaveChanges() only on entity from one side. So your Member starts to refer another BankAccount while your BankAccounts still refer to the old Member. You need to mark all appropriate BankAccounts as modified along with your modified Member in the same place and then call SaveChanges() so everything will be saved (from comment).
To prevent adding a duplicate you can try to set the state of your entities to the State.Modified instead of State.Added.
The reason of that problem was that you were updating only entity from one side. If you have BankAccounts-Members relationship then in case you update the navtigation property for Member you should update a navigation property for BankAccount too and vice versa. If you just update some property (Member.Name or anything) you just set this Member's State to State.Modified without affecting any of other Member's, BankAccount's etc.
If the entity tracking is turned on for you then EF will automatically track entities that were modified and set appropriate states for them. But as I've seen from your issue, it's turned off for you so you have to manually set the state for each object you want to add/update/delete.
Currently, I'm sending some data to Parse.com. All works well, however, I would like to add a row if it's a new user or update the current table if it's an old user.
So what I need to do is check if the current Facebook ID (the key I'm using) shows up anywhere in the fbid column, then update it if case may be.
How can I check if the key exists in the column?
Also, I'm using C#/Unity.
static void sendToParse()
{
ParseObject currentUser = new ParseObject("Game");
currentUser["name"] = fbname;
currentUser["email"] = fbemail;
currentUser["fbid"] = FB.UserId;
Task saveTask = currentUser.SaveAsync();
Debug.LogError("Sent to Parse");
}
Okay, I figured it out.
First, I check which if there is any Facebook ID in the table that matches the current ID, then get the number of matches.
public static void getObjectID()
{
var query = ParseObject.GetQuery("IdealStunts")
.WhereEqualTo("fbid", FB.UserId);
query.FirstAsync().ContinueWith(t =>
{
ParseObject obj = t.Result;
objectID = obj.ObjectId;
Debug.LogError(objectID);
});
}
If there is any key matching the current Facebook ID, don't do anything. If there aren't, just add a new user.
public static void sendToParse()
{
if (count != 0)
{
Debug.LogError("Already exists");
}
else
{
ParseObject currentUser = new ParseObject("IdealStunts");
currentUser["name"] = fbname;
currentUser["email"] = fbemail;
currentUser["fbid"] = FB.UserId;
Task saveTask = currentUser.SaveAsync();
Debug.LogError("New User");
}
}
You will have to do a StartCoroutine for sendToParse, so getObjectID has time to look through the table.
It may be a crappy implementation, but it works.
What you need to do is create a query for the fbid. If the query returns an object, you update it. If not, you create a new.
I'm not proficient with C#, but here is an example in Objective-C:
PFQuery *query = [PFQuery queryWithClassName:#"Yourclass]; // Name of your class in Parse
query.cachePolicy = kPFCachePolicyNetworkOnly;
[query whereKey:#"fbid" equalTo:theFBid]; // Variable containing the fb id
NSArray *users = [query findObjects];
self.currentFacebookUser = [users lastObject]; // Array should contain only 1 object
if (self.currentFacebookUser) { // Might have to test for NULL, but probably not
// Update the object and save it
} else {
// Create a new object
}
I have a project that inserts personal information to a table and details into another table. But sometimes personal information cannot be recorded, however details are recorded. As below code part, firstly personal information are inserted, then details. But sometimes personal information doesn't get saved and userId returns 0, So details are saved. I don't know why it doesn't work. Any idea?
public int ConferenceIdyeGoreKisiBilgileriniKaydet(string orderId)
{
KisiselBilgilerBal kisiBilgileri = (KisiselBilgilerBal)Session["kisiselBilgilerSession"];
registrationCode = GenerateGeristrationCode();
string toplamMaliyet = Session["toplamOdeme"].ToString();
PersonalInformation.SavePersonalInformations(kisiBilgileri, registrationCode,conferenceName);
int userId = AuthorPaperDetaylari.AdVeSoyadaGoreIdGetir(kisiBilgileri.f_name, kisiBilgileri.l_name);
AuthorPaperDetaylari.SaveAuthorPaperDetails(authorPaperDetay, userId); // save details via userId.
return userId;
}
This method saves personal information.
public static void SavePersonalInformations(KisiselBilgilerBal kisiBilgileri,string registrationCode,string conferenceName)
{
try
{
string cs = ConfigurationManager.AppSettings["SiteSqlServer"];
DBDataContext db = new DBDataContext(cs);
DBpersonalInformation personalInfo = new DBpersonalInformation();
personalInfo.f_name = kisiBilgileri.f_name;
personalInfo.l_name = kisiBilgileri.l_name;
personalInfo.university_affiliation = kisiBilgileri.university_affiliation;
personalInfo.department_name = kisiBilgileri.department_name;
personalInfo.address1 = kisiBilgileri.address1;
personalInfo.address2 = kisiBilgileri.address2;
personalInfo.city = kisiBilgileri.city;
personalInfo.state = kisiBilgileri.state;
personalInfo.zipCode = kisiBilgileri.zipCode;
personalInfo.country = kisiBilgileri.country;
personalInfo.phone = kisiBilgileri.phone;
personalInfo.email = kisiBilgileri.email;
personalInfo.orderId = kisiBilgileri.orderId;
personalInfo.registrationCode = registrationCode;
personalInfo.date = DateTime.Now;
personalInfo.conferenceName = conferenceName;
db.DBpersonalInformations.InsertOnSubmit(personalInfo);
db.SubmitChanges();
}
catch (Exception)
{
}
}
This method saves details
public static void SaveAuthorPaperDetails(AuthorPaperDetailsBal authorPaperDetay, int userId)
{
try
{
string cs = ConfigurationManager.AppSettings["SiteSqlServer"];
DBWebDataContext db = new DBWebDataContext(cs);
DBAuthorPaperDetail authorPaperDetail = new DBAuthorPaperDetail();
authorPaperDetail.paper_title = authorPaperDetay.paperTitleDetails;
authorPaperDetail.conference_maker_id = authorPaperDetay.confMakerId;
authorPaperDetail.additional_paper_title = authorPaperDetay.additionalPprTtle;
authorPaperDetail.areYouMainAuthor = authorPaperDetay.mainAuthor;
authorPaperDetail.feeForFirstAuthorPaper = authorPaperDetay.registerFeeForFirstAuthor;
authorPaperDetail.feeForAdditionalPaper = authorPaperDetay.regFeeForAdditionalPape;
authorPaperDetail.feeForParticipCoAuthors = authorPaperDetay.regFeeForCoAuthors;
authorPaperDetail.userId = userId;
authorPaperDetail.firstCoAuthorName = authorPaperDetay.firstCoAuthor;
authorPaperDetail.secondCoAuthorName = authorPaperDetay.secondCoAutho;
authorPaperDetail.thirdCoAuthorName = authorPaperDetay.thirdCoAuthor;
authorPaperDetail.toplamOdeme = authorPaperDetay.toplamMaliyet;
db.DBAuthorPaperDetails.InsertOnSubmit(authorPaperDetail);
db.SubmitChanges();
}
catch (Exception)
{
}
}
I don't know why it doesnt work. Any idea?
...
catch (Exception)
{
}
Well, that explains pretty much everything... don't do this. Ever. The database layer is trying to tell you what the problem is, and you are sticking your fingers in your ears, hoping that'll make it go away. If I had to guess: maybe an occasional timeout due to being blocked by another SPID.
If you can't do anything useful or appropriate with an exception, just let it bubble to the caller. If it gets to the UI, tell the user about it (or just log the issue internally and tell the user "There was a problem").
Also, a LINQ-to-SQL data-context is IDisposable; you should have using statement around db.
In addition to Marc's answer... You are calling SubmitChanges twice. If you want atomic data storage, you should call it once. You can use relational properties to create an object graph, and submit the whole graph at once.
public void SaveParentAndChildren()
{
using (CustomDataContext myDC = new CustomDataContext())
{
Parent p = new Parent();
Child c = new Child();
p.Children.Add(c);
myDC.Parents.InsertOnSubmit(p); //whole graph is now tracked by this data context
myDC.SubmitChanges(); // whole graph is now saved to database
// or nothing saved if an exception occurred.
} //myDC.Dispose is called for you here whether exception occurred or not
}
The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: 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.
Is the error message i get. here are the two functions i use...
public IList<string> GenerateVersions(decimal id, decimal fId, string folderName, string filename, string objFile)
{
List<string> generatedFiles = new List<string>();
foreach (var tCmdSets in db.IMG_SETTINGS_CMDSETS.Where("it.SETTINGS_FOLDER_ID = #folderid", new ObjectParameter("folderid", id)))
{
var strDestinationPath = ImageResizer.Util.PathUtils.RemoveExtension(Path.Combine(tmpDefaultFolder, tCmdSets.SETTINGS_CMDSET_DESTINATION, filename));
ResizeSettings objResizeCommand = new ResizeSettings(tCmdSets.SETTINGS_CMDSET_COMMAND);
var strCreatedFile = ImageBuilder.Current.Build(objFile, strDestinationPath, objResizeCommand, false, true);
generatedFiles.Add("### File created: (" + folderName + " » " + tCmdSets.SETTINGS_CMDSET_NAME + " ») " + Path.GetFileName(strCreatedFile));
IMG_UPLOAD_GENERATED_FILES tObjGenerated = new IMG_UPLOAD_GENERATED_FILES();
tObjGenerated.UPLOAD_GENERATED_FILE_NAME = Path.GetFileName(strCreatedFile);
tObjGenerated.UPLOAD_GENERATED_PATH = Path.GetDirectoryName(strCreatedFile);
tObjGenerated.SETTINGS_CMDSET_ID = tCmdSets.SETTINGS_CMDSET_ID;
tObjGenerated.UPLOAD_FILE_ID = fId;
dbHandler.IMG_UPLOAD_GENERATED_FILES.AddObject(tObjGenerated);
dbHandler.SaveChanges();
}
return generatedFiles;
}
public ActionResult UploadBulkFiles(decimal id)
{
IMG_SETTINGS_FOLDERS img_settings_folders = db.IMG_SETTINGS_FOLDERS.Single(i => i.SETTINGS_FOLDER_ID == id);
string strBulkDirectory = Path.Combine(tmpDefaultFolder, img_settings_folders.SETTINGS_FOLDER_BULK);
string[] objFiles = Directory.GetFiles(strBulkDirectory);
List<string> lstOuput = new List<string>();
foreach (var tFile in objFiles)
{
System.IO.File.Move(tFile, Path.Combine(tmpDefaultFolder, "masters", img_settings_folders.SETTINGS_FOLDER_NAME, Path.GetFileName(tFile)));
lstOuput.Add("### File moved to masters (" + img_settings_folders.SETTINGS_FOLDER_NAME + " ») " + Path.GetFileName(tFile));
IMG_UPLOAD_FILES tObjUploadedFile = new IMG_UPLOAD_FILES();
tObjUploadedFile.UPLOAD_FILE_NAME = Path.GetFileName(tFile);
tObjUploadedFile.SETTINGS_FOLDER_ID = img_settings_folders.SETTINGS_FOLDER_ID;
dbHandler.IMG_UPLOAD_FILES.AddObject(tObjUploadedFile);
dbHandler.SaveChanges();
var objGeneratedFiles = GenerateVersions(img_settings_folders.SETTINGS_FOLDER_ID,tObjUploadedFile.UPLOAD_FILE_ID, img_settings_folders.SETTINGS_FOLDER_NAME, Path.GetFileName(tFile), Path.Combine(tmpDefaultFolder, "masters", img_settings_folders.SETTINGS_FOLDER_NAME, Path.GetFileName(tFile)));
lstOuput.AddRange(objGeneratedFiles);
}
if (lstOuput.Count > 0)
{
return PartialView("UploadSingleFile", lstOuput);
}
else
{
return PartialView("NoUploads");
}
}
DATA MODEL
IMG_UPLOAD_FILE
UPLOAD_FILE_ID (PK)
UPLOAD_FILE_NAME
SETTINGS_FOLDER_ID
IMG_UPLOAD_GENERATED_FILES
UPLOAD_GENERATED_FILE_ID (PK)
UPLOAD_GENERATED_FILE_NAME
UPLOAD_GENERATED_FILE_PATH
SETTINGS_CMDSET_ID
UPLOAD_FILE_ID
I had the exact same scenario with Entity Model based on Oracle database. The implementation of Identity is done by trigger so when adding the tables to the model it does not set the StoreGenertedPattern property of the identity column to Identity since it doens't aware that this column is identity.
There is a need to open model editor, locate the entity in the model, click on the key column and set the StoreGenertedPattern property to 'Identity' manually.
The closest I can come to finding an answer is:
Because Oracle uses a Sequence + Trigger to make "Auto Ident" values, it seems like when the entity framework adds an object at saves it, the value return is still 0, because the trigger/sequence haven't updated it yet.
Because of the 0 number, the ObjectMannager will think that multiple objects with the entity key of 0 are in conflict.
I don't have a "bullet proof" solutions, but have rewritten my solutions to handle it another way.
\T
This might not be related to your problem but I was getting this problem on a web page with an ajax manager running until I did this:
...
private static _objectContext;
protected void Page_Init(object sender, EventArgs e)
{
_objectContext = new ObjectContext();
}
...
protected void _ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)
{
e.Context = _objectContext;
}
protected void _ContextDisposing(object sender, EntityDataSourceContextDisposingEventArgs e)
{
e.Cancel = true;
}
Creating the ObjectContext in Page_Load when not a postback caused that very exception for me.
I'm tryring to do a simple insert with foreign key, but it seems that I need to use db.SaveChanges() for every record insert. How can I manage to use only one db.SaveChanges() at the end of this program?
public static void Test()
{
using (var entities = new DBEntities())
{
var sale =
new SalesFeed
{
SaleName = "Stuff...",
};
entities.AddToSalesFeedSet(sale);
var phone =
new CustomerPhone
{
CreationDate = DateTime.UtcNow,
sales_feeds = sale
};
entities.AddToCustomerPhoneSet(phone);
entities.SaveChanges();
}
}
After running the above code I get this exception:
System.Data.UpdateException: An error occurred while updating the entries. See the InnerException for details. The specified value is not an instance of a valid constant type
Parameter name: value.
EDIT: Changed example code and added returned exception.
Apperantly using UNSIGNED BIGINT causes this problem. When I switched to SIGNED BIGINT everything worked as it supposed to.
I tried to do this "the right way":
And then I wrote this little test app to scan a directory, store the directory and all its files in two tables:
static void Main(string[] args)
{
string directoryName = args[0];
if(!Directory.Exists(directoryName))
{
Console.WriteLine("ERROR: Directory '{0}' does not exist!", directoryName);
return;
}
using (testEntities entities = new testEntities())
{
StoredDir dir = new StoredDir{ DirName = directoryName };
entities.AddToStoredDirSet(dir);
foreach (string filename in Directory.GetFiles(directoryName))
{
StoredFile stFile = new StoredFile { FileName = Path.GetFileName(filename), Directory = dir };
entities.AddToStoredFileSet(stFile);
}
try
{
entities.SaveChanges();
}
catch(Exception exc)
{
string message = exc.GetType().FullName + ": " + exc.Message;
}
}
}
As you can see, I only have a single call to .SaveChanges() at the very end - this works like a charm, everything's as expected.
Something about your approach must be screwing up the EF system.....
it might be related with the implementation of AddToSalesFeedSet etc..
there is chance that you are doing commit inside ?
any way, my point is that i encountered very close problem, was tring to add relation to new entity with existed entity that been queried earlier - that has unsigned key
and got the same exception;
the solution was to call Db.collection.Attach(previouslyQueriedEntityInstance);