Insert exception when using linqtosql - linq-to-sql

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.

Related

Duplicate id in Go gorm many2many

I am having an issue with saving many2many in gorm with go. The problem is that I want a book to have multiple genres, but when I try to use the Association method to add genres to the books,
I get the following error
Error 1062: Duplicate entry '2debe760-2cf8-4dff-80dd-a912ff6f8176' for key 'book_id'
I do know that the SQL generated by the gorm is false which gives the error above. The question is what should I do to avoid the check for "where not exist"? That check is not needed at all for many to many relationship. I dont understand the purpose of the check.
INSERT INTO `book_genres` (`book_id`,`genre_id`) SELECT 'e038ba55-ecd9-41a3-a1ea-36da86d465ea','3df46a42-c1ce-416c-b246-753b81fc2246' FROM DUAL WHERE NOT EXISTS (SELECT * FROM `book_genres` WHERE `book_id` = 'e038ba55-ecd9-41a3-a1ea-36da86d465ea' AND `genre_id` = '3df46a42-c1ce-416c-b246-753b81fc2246')
This is my setup, what I am missing to ensure I don't get the error?
type Book struct {
Identifiable
Name string `sql:"type:varchar(255);not null" json:"name"`
Pages int `sql:"type:integer;not null"`
AuthorId uuid.UUID `sql:"type:varchar(36);foreign_key"`
Genres []Genre `gorm:"many2many:book_genres;"`
}
type Genre struct {
Identifiable
Name string `sql:"type:varchar(255);not null" json:"name"`
Books []*Book
}
var auth domain.Author;
auth.Age = 59;
auth.Name = "Fyodor Dostoyevsky";
fmt.Println(auth)
var drama domain.Genre
drama.Name = "Drama"
var thriller domain.Genre
thriller.Name = "Thriller"
var genres []domain.Genre
genres = append(genres, drama, thriller)
engine.Save(&drama)
engine.Save(&thriller)
var book1 domain.Book;
book1.Name = "Idiot";
book1.Pages = 11000;
book1.AuthorId = auth.Id;
var book2 domain.Book;
book2.Name = "Crime and Murder";
book2.Pages = 854;
book2.AuthorId = auth.Id;
engine.Save(&auth)
engine.Model(&auth).Association("Books").Append(&book2)
engine.Model(&auth).Association("Books").Append(&book1)
err := engine.Debug().Model(&book1).Association("Genres").Append([]domain.Genre{drama, thriller});
if err != nil {
fmt.Println(err)
}

The INSERT statement conflicted with the FOREIGN KEY constraint2

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.

Linq to sql error inserting value

I am trying to do an insert using linq to sql but am getting the following error
Additional information: Cannot insert the value NULL into column 'UserID', table 'Itiss_Request.dbo.Users'; column does not allow nulls. INSERT fails.
The UserID table is the pk aswel as the identity has been set to autoincrement.
The database has 4 fields.
DataClasses1DataContext dt = new DataClasses1DataContext();
User usr = new User();
usr.MudID = a[1];
usr.Email = Session["email"].ToString();
usr.Name = Session["userName"].ToString();
dt.Users.InsertOnSubmit(usr);
dt.SubmitChanges();
This is an from my context file
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_UserID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int UserID
{
get
{
return this._UserID;
}
set
{
if ((this._UserID != value))
{
this.OnUserIDChanging(value);
this.SendPropertyChanging();
this._UserID = value;
this.SendPropertyChanged("UserID");
this.OnUserIDChanged();
}
}
}
Please try this...
DataClasses1DataContext dt = new DataClasses1DataContext();
User usr = new User();
usr.MudID = a[1];
usr.Email = Session["email"].ToString();
usr.Name = Session["userName"].ToString();
dt.Users.AddObject(usr);
dt.SaveChanges();

Insert into table if two keys do not exist

I have a table that maps itemId(item.id) and tagId(tag.id).
I'm writing a query that needs to insert a new row, but only if BOTH itemId and tagId do not already have an entry. What's the best way to do this?
Here is my current query that doesn't already check for an existing match:
// create tag-item maps
$sql = 'INSERT INTO item_tag
SELECT :itemId AS iid, tag.id AS tid
FROM tag
WHERE tag.name=:name';
try{
$stmt = $db->dbh->prepare($sql);
for($i = 0; $i < $count; $i++) {
$data = array(':itemId' => $itemId, ':name' => $tags[$i]);
$result = $stmt->execute($data);
if($result !== false) {
// Do nothing
}else {
return false;
}
}
return true;
}catch(PDOException $e) {
logit($e->getMessage());
return false;
}
A UNIQUE constraint would be the ideal solution, and according to the docs the MyISAM engine supports them.
ALTER TABLE item_tag ADD CONSTRAINT item_tag_iid_tid_uq UNIQUE (iid, tid);
Then if your INSERT tries to add a duplicate (iid, tid) pair it will throw and you can handle it in your catch code.
If you don't want to do the UNIQUE constraint, you could instead add an "existence" check to your INSERT query:
INSERT INTO item_tag
SELECT :itemId AS iid, tag.id AS tid
FROM tag
WHERE tag.name=:name' AND NOT EXISTS (
SELECT * FROM item_tag WHERE iid=:itemId AND tid=tag.id)
I tested this using my own differently-named tables, so hopefully I "translated" it correctly to your table/column names.

DateTime error when updating rows using EF

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);
}