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)
}
Related
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.
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);
}
in my db,i have 4 tables employee,customer,product & orders.
i m trying linq to sql and wrote the following expression:
NorthwindDataContext db = new NorthwindDataContext();
var matchingEmployees = from employee in db.Employees
where employee.emp_city = "pune"
select employee;
but it reflects following error:
Error 1 Cannot implicitly convert type 'string' to 'bool'
i have given emp_city as nvarchar(50)
how to resolve the problem
NorthwindDataContext db = new NorthwindDataContext();
var matchingEmployees = from employee in db.Employees
where employee.emp_city == "pune" // == not =
select employee;
I have a table of Contacts, and a table of Groups which has a many-to-many relationship managed by a simple contacts_groups table:
contacts_groupsID Identity INT
ContactID INT
GroupID INT
I have a delimted String of contact IDs e.g. "1|23|987|2346|33|9821|" which I need to insert into the contacts_groups table (along with the groupID). I am using LinQ to SQL and C#, but want to know the most efficient way of looping through the delimited string (probably .Split()) checking for duplicates and inserting if not exist.
List<int> requested = contactIds.Split('|')
.Select(s => int.Parse(s))
.Distinct()
.ToList();
List<int> existing = (
from x in db.GroupsContacts
where x.GroupId == groupId
select x.ContactId
).ToList();
List<int> toBeAdded = requested.Except(existing).ToList();
foreach(int id in toBeAdded)
{
GroupsContacts record = new GroupsContacts();
record.GroupID = groupID;
record.ContactID = id;
db.InsertOnSubmit(record);
}
db.SubmitChanges();
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.