The INSERT statement conflicted with the FOREIGN KEY constraint "fk_JOB_POSTING_CLIENT". The conflict occurred in database "ResLand", table "dbo.CLIENT", column 'ID'. The statement has been terminated.
i got above exception message while i am inserting the data in job posting screen
my database design for job_posting table is:
INSERT INTO [dbo].[JOB_POSTING]
([COMP_ID]
,[RES_ID]
,[RES_TYPE]
,[CONTACT_NAME]
,[CONTACT_INFO]
,[TITLE]
,[DESCR]
,[PREREQUISITES]
,[SKILLS]
,[JOB_TYPE]
,[LOCATION]
,[DURATION]
,[POST_DT]
,[POST_END_DT]
,[POSITIONS_CNT]
,[CLIENT_ID]
,[CATEGORY]
,[RATE]
,[PERKS]
,[STAT]
,[IS_DELETED]
,[CR_BY]
,[DT_CR]
,[MOD_BY]
,[DT_MOD])
in my controller i wrote the code like this :
[ValidateInput(false)]
//[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult PostJob(PostJobModel model, string btn)
{
if (btn == "Save")
{
JOB_POSTING jobPost = new JOB_POSTING();
jobPost.RES_ID = RL_Constants.RES_ID;
jobPost.RES_TYPE = RL_Constants.RES_TYPE;
jobPost.COMP_ID = RL_Constants.COMP_ID;
jobPost.POST_DT = Convert.ToDateTime(model.POST_DT);
jobPost.POST_END_DT = Convert.ToDateTime(model.POST_END_DT);
jobPost.POSITIONS_CNT = Convert.ToInt32(model.POSITIONS_CNTS);
jobPost.JOB_TYPE =Convert.ToString(model.JOB_TYPE);
jobPost.DURATION = model.DURATION;
jobPost.CATEGORY = Convert.ToString(model.CATEGORY_ID);
jobPost.PREREQUISITES = model.PREREQUISITES;
jobPost.LOCATION = model.LOCATION;
jobPost.RATE = model.RATE;
//CLIENT=model.CLIENT_ID
//CLIENT_ID=(model.CLIENT_ID)
jobPost.TITLE = model.POST_TITLE;
jobPost.DESCR = Regex.Replace(model.DESCRIPTION, #"<[^>]+>| ", "");
jobPost.CONTACT_NAME = model.CONTACT_PERSON;
jobPost.CONTACT_INFO = model.CONTACT_PHONE + "/" + model.CONTACT_EMAIL;
jobPost.SKILLS = model.SKILLS;
jobPost.PERKS = model.PERKS;
jobPost.DT_CR = DateTime.Now;
jobPost.CR_BY = RL_Constants.USER_NAME;
jobPost.STAT = "ACTIVE";
jobPost.IS_DELETED = "N";
reslandentity.JOB_POSTING.Add(jobPost);
reslandentity.SaveChanges();
}
return RedirectToAction("JobSearchList", "Employer");
}
where is the problem
The error message says that the client Id you're using doesn't exist in the Client table. Are you setting the cliendId fk reference correctly? In the code you've posted the setting of clientId has been commented out. This means that the clientId = 0 (if it's an int), and I bet you don't have any clients with id = 0.
---- Update -----
As your clientId = 0 it tries to make a fk relationship to the client table, which fails. You said you didn't want to use the clientId at this point and that the clientId column was nullable. I'm not sure why it's assigned the 0 value, but just to check that it's working you should do a clientId = null in your mapping. This should prevent EF from trying to make a fk relationship.
Related
I have a method that gets an existing row from a table in my database and updates some values on it and then save those changes. The table in quesiton has these columns:
The code that does the updating is here:
public void Update(Accommodation accommodation, string code, int supplierId)
{
var existingAccommodation = Get(a => a.Code == code && a.SupplierId == supplierId);
DateTime now = DateTime.Now;
existingAccommodation.ModifiedDate = now;
existingAccommodation.Description = accommodation.Description;
existingAccommodation.Introduction = accommodation.Introduction;
existingAccommodation.Name = accommodation.Name;
existingAccommodation.Strapline = accommodation.Strapline;
existingAccommodation.Type = accommodation.Type;
existingAccommodation.Processed = true;
DataContext.SaveChanges();
}
The problem is that the line DataContext.SaveChanges(); causes an exception whose innerexception says:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value
This is where the above code is called
Accommodation existingAccommodation = GetByCode(code, supplierId);
if (existingAccommodation != null)
{
_accommodationRepository.Update(
accommodation, code, existingAccommodation.SupplierId);
}
When I try to use the function '->lastInsertId()' to retrieve the lat ID of a table I get back '0'.
I can't find the solution. My table is an autoincrement
I try to get it in the controller with this code.
$reviews = new Application_Model_DbTable_Reviews();
$lastId = $reviews->getAdapter()->lastInsertId();
echo $lastId;
I hope someone can help me.
With kind regards,
Nick
Well this stuff is not mention in docs but it works for e.g
if you have table name 'Book' with PK book_id , FK user_id and 'User' table with PK user_id
<<Book>>
*book_id
title
user_id
<<User>>
*user_id
name
age
then
$userTb = new Model_DbTable_User();
$user = $userTb->createRow();
$user->name = "jason";
$user->age = 25;
$user->save();
//well after saving the record ZF populates PK for you so now you have read only access to auto incremented PK simply by $userTb->user_id;
so
$bookTb = new Model_DbTable_Book();
$book = $bookTb->createRow();
$book->title = 'php';
$book->user_id = $user->user_id;
$bookId = $book->save(); // this is another way of accessing auto generated PK at insert tim .
May anybody tell me how to replace this code using Linq ?
using using Microsoft.Practices.EnterpriseLibrary.Data;
Public IDataReader GetRowByRowData()
{
Database Db = DatabaseFactory.CreateDatabase();
string sqlString = "SELECT * FROM TableTest";
DbCommand DbCmd = PpwDb.GetSqlStringCommand(sqlString);
Db .ExecuteReader(DbCmd);
}
Please help to get row by row data from table TableTest using Linq
you can do that like this:
var myQyery=from a in dataContext.Mytable
select a;
foreach(var item in myQuery)
{
//what you like
}
var records = (from p in context.TableTest
select p).ToList();
foreach(var record in records) {
// loop through each record here
}
ToList method will query the database and get the result set.
I load the primary key from my table into a list. Depending on the size of the data set and the primary key, loading into a list does not take too long. After loading the keys, use FirstOrDefault() with a where clause like so:
var keys = Db.TableTest.Select(x => x.primaryKey).ToList();
foreach (var k in keys)
{
var record = (from i in Db.TableTest
where i.primaryKey == k
select new
{
//Select only the columns you need to conserve memory
col1 = i.col1,
col2 = i.col2
}).FirstOrDefault();
//Process the record
}
I have an error updating my database because of variables. This is my code:
UPDATE `payment` SET `paid`=1 AND `amoun`=$amountpaid WHERE `paid`=0 AND `userid`=$uid
$amountpaid is the amount of the bill that the user paid and $uid is user id. It seems like using $ in front of variable names is forbidden. How can I use variables in SQL?
Where are your variables coming from? You probably want something like this if you're using JDBC:
int setPaid = 1;
int amountPaid = x; // put $amountpaid here
int wherePaid = 0;
int userId = y; // put $uid here
String updateQuery = "UPDATE payment SET paid = ?, amoun = ?"
+ " WHERE paid = ? AND userid = ?";
PreparedStatement ps = con.prepareStatement(updateQuery);
ps.setInt(1, setPaid);
ps.setInt(2, amountPaid);
ps.setInt(3, wherePaid);
ps.setInt(4, userId);
ps.executeUpdate();
I got the solution by using String.
I converted the ArrayList to a String and then sent the data as string. The data got updated but I don't know what will happen next if I want to view the data in the client tier...
When I want to Insert data in my table this Exception appeared
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Message_Subject". The conflict occurred in database "C:\DOCUMENTS AND SETTINGS\TEHRANI\DESKTOP\MESSAGEADMINPAGE\APP_DATA\ASPNETDB.MDF", table "dbo.Subject", column 'ID_Subject'.
The statement has been terminated.
This Code for Insert :
string[] a = UserIDtxt.Text.Split(',');
foreach (String b in a)
{
Message M = new Message();
Guid i = (from q in MDB.aspnet_Memberships
where q.aspnet_User.UserName.ToString() == b.ToString()
select q).Single().UserId;
M.ID_Receiev = i;
M.ID_Message = Guid.NewGuid();
M.ID_Sender = (Guid)Admin.ProviderUserKey;
M.ID_Message_Parent = Guid.Empty;
if (SubjectDDL.SelectedItem.ToString() != "Other")
{
M.ID_Subject = new Guid(SubjectDDL.SelectedValue);
}
else
{
M.Other_Subject = Othertxt.Text;
}
M.Body = TEXTtxt.Text;
M.Date = DateTime.Now;
M.IsFinished = false;
M.IsRead = false;
MDB.Messages.InsertOnSubmit(M);
}
MDB.SubmitChanges();
you must set value all of feild
if (SubjectDDL.SelectedItem.ToString() != "Other")
{
M.ID_Subject = new Guid(SubjectDDL.SelectedValue);
M.Other_Subject = null;
}
else
{
M.ID_Subject = new Guid(SubjectDDL.SelectedValue);
M.Other_Subject = Othertxt.Text;
}
For what I can tell, based in the FOREIGN KEY constraint "FK_Message_Subject", you also have a table to Subjects. If this assumption is correct, when you assign M.ID_Subject a new Guid, it might not exist as a FOREIGN KEY in the Subjects table. You must find any existing Subject with the SubjectDDL.SelectedValue and retrieve the existing ID for the FOREIGN KEY. If it doesn't exist, create a new Subject and assign it directly to the Message M.
The same applies to when SubjectDDL.SelectedItem.ToString() == "Other". In this case, the FOREIGN KEY is null and it might be causing this error also.