The MERGE statement conflicted with the CHECK constraint - Entity framework - sql

I have the following code updating the place table with entity framework. Place table has Check constraint on column SequenceNumber. ([SequenceNumber]>=(1))
I am trying to update the table with entity framework but when i try to update it gives me error:
SqlException: The MERGE statement conflicted with the CHECK constraint "CK_Places_SequenceNumber". The conflict occurred in database "XXX", table "dbo.Places", column 'SequenceNumber'.
Below is the code. Just to try I even commented SequenceNumber assignment to avoid the update but i think it depends on the underlying state of entity as well.
var places = placeDtos.Select(x => new Place
{
PlaceId = x.PlaceId,
Name = x.Name,
SequenceNumber = x.SequenceNumber,
PlaceAreaId = areaId,
PlaceInterestPlaces = x.PlaceInterests?.Select(d => new PlaceInterestPlace
{
PlaceId = x.PlaceId,
PlaceInterestId = d.PlaceInterestId
})?.ToList()
})?.ToList();
_dbContext.Places.UpdateRange(desks);
await _dbContext.SaveChangesAsync();
Can someone help in making me understand whats the problem here? Thanks.

Related

Postgres - UPDATE ON CONFLICT not-null constraint violation

I am trying to use UPDATE .. ON CONFLICT available from Postgres 9.5 but I have a problem with violating null constraint on id.
I get:
ERROR: null value in column "id" of relation "feed" violates not-null constraint
Basically when id = null (feedId) I would like to perform INSERT and if id is returned to run an UPDATE.
Also I have WHERE clause in that query that it should be used only when there is an ID and not use when not because when adding it I also got an error that column reference \"id\" is ambiguous. It there a fix to my query or there is an alternative?
Without WHERE clause UPDATE is working and INSERT is not. But in the original case I posted below I have trouble with both errors.
I am new with writing sql queries and solutions I found online did not helped me with my case.
"INSERT INTO feed (id, team_id, name, url, auto_approve, last_pulled_at, source, evergreen)
VALUES (:feedId, :teamId, :name, :url, :autoApprove, :lastPulledAt, :source, :evergreen)
ON CONFLICT (id)
DO UPDATE SET
id = :feedId,
team_id = :teamId,
name = EXCLUDED.name,
url = EXCLUDED.url,
auto_approve = EXCLUDED.auto_approve,
last_pulled_at = EXCLUDED.last_pulled_at,
source = EXCLUDED.source,
evergreen = EXCLUDED.evergreen
WHERE id = :feedId
AND team_id = :teamId"

How to avoid System.Data.Entity.Infrastructure.DbUpdateException when doing migration

I have one database and I need to do migration, in other words I need to move the data to another database. I have used EF, and generated automatically the classes with EDO. The problem occures at newDb.SaveChanges()
Here is my code:
var oldDb = new oldBAEntity();
var newDb = new NewDbContextEntities();
var query2 = oldDb.R_ClaimHistory.ToList();
foreach (var sourceObj in query2)
{
ClaimComment targetobj = new ClaimComment();
targetobj.ClaimId = (int)sourceObj.IdClaim;
targetobj.Comment = sourceObj.HistClaimDescription;
targetobj.UserCreated = (int)sourceObj.IdUserCreated;
targetobj.DateCreated = sourceObj.DateCreated;
newDb.ClaimComments.Add(targetobj);
}
newdb.SaveChanges();
When I run it, I am getting this error :
System.Data.Entity.Infrastructure.DbUpdateException
InnerException :
The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_ClaimComments_Claims\". The conflict occurred in database \"Toni-Bank-DB\", table \"dbo.Claims\", column 'ID'.\r\nThe statement has been terminated.
You appear to be attempting to insert a new ClaimComment when the Claims.ID does not exist (or does not match).
You will need to re-order your code to ensure all FKs exist before attempting to add a record which has the constraint defined.
Before inserting to ClaimComment table you need to have corresponding ClaimId in Claim table. So First make sure Master table data are inserted and then go for child tables.

SQL Delete Query Foreign Key constraint

I am trying to Delete record with primary key as foreign key in two tables. Everytime I try to run the query it gives me this error:
Query:
DELETE FROM BusinessPlus_Post
FROM BusinessPlus_Post
INNER JOIN BusinessPlus_PostImage ON BusinessPlus_Post.Post_ID = BusinessPlus_PostImage.BusinessPlusPost_ID
INNER JOIN BusinessPlus_PostTag ON BusinessPlus_Post.Post_ID = BusinessPlus_PostTag.BusinessPlusPost_ID
WHERE
(BusinessPlus_Post.Post_ID = 3)
AND (BusinessPlus_PostImage.BusinessPlusPost_ID = 3)
AND (BusinessPlus_PostTag.BusinessPlusPost_ID = 3)
Error:
The DELETE statement conflicted with the REFERENCE constraint
"FK_BusinessPlusPostImage". The conflict Occurred in database
"BusinessPlus_AdminPanel_Database", table
"dbo.BusinessPlus_PostImage", column 'BusinessPlusPost_ID'. The
statement was terminated.
Right now, you are only stating that you want to delete the BusinessPlus_Post record, but not the BusinessPlus_PostImage and BusinessPlus_PostTag records. This would lead to problems, as we then would have 'orphan' PostImage and PostTag records with no corresponding Post records.
Apparently, it is not possible to delete from multiple tables in SQL Server (it is supported in MySQL, for example).
You have to split your queries, and delete from the 'child' tables first:
DELETE FROM BusinessPlus_PostImage
WHERE BusinessPlusPost_ID = 3
DELETE FROM BusinessPlus_PostTag
WHERE BusinessPlusPost_ID = 3
DELETE FROM BusinessPlus_Post
WHERE Post_ID = 3
Error: The DELETE statement conflicted with the REFERENCE constraint
"FK_BusinessPlusPostImage". The conflict Occurred in database
"BusinessPlus_AdminPanel_Database", table
"dbo.BusinessPlus_PostImage", column 'BusinessPlusPost_ID'. The
statement was terminated.
Error denotes that you have data referencing the foreign ,hence you cannot delete.
Delete the datas in BusinessPlus_AdminPanel_Database table
dbo.BusinessPlus_PostImage, column BusinessPlusPost_ID ,and then try delete

An error occurred while entries were being updated.

First of all, Sorry for the bad english.
I'm working on a university project with EF 4.0. Everytime i want to delete an entity item from the collection i get the error : "An error occurred while entries were being updated."
I have foreign keys.
I can't post images because i justa have 1 point of rep, so i can't show you de diagramas.
private void Elimina_Pais_btn_Click(object sender, RoutedEventArgs e)
{
int IdPaisABorrar = ((Pais)Tabla_Paises_DataGrid.SelectedItem).Id;
MundialEntities db = new MundialEntities();
Pais PaisABorrar = db.Paises.Single(p => p.Id == IdPaisABorrar);
if(PaisABorrar != null)
db.Paises.Remove(PaisABorrar);
db.SaveChanges();
UpdatePaises();
}
Inner Exception {"The DELETE statement conflicted with the REFERENCE constraint \"FK_Pais_Visita\". The conflict occurred in database \"Mundial\", table \"dbo.Partido\", column 'IdVisita'.\r\nThe statement has been terminated."}
Thank You very Much
You are trying to delete (remove) a record that is still being used in another table. So unless cascade delete can be setup on this record type, you will need to remove the other record/s at the sametime or before.
Either you can you cascade delete in your migration table or you can load the entities to delete them
Something like (believing that you have some table called as Visita (replace it with your table name)
Pais PaisABorrar = db.Paises
.Include(p => p.Visita)
.Single(p => p.Id == IdPaisABorrar);
The statement Include(p => p.Visita) will load all the related entries and then they will be deleted by call db.Paises.Remove(PaisABorrar);
NOTE: If this had helped you then dont forgot to vote it up and mark it as answer

Inserting to a table with an identity column

I am trying to insert a row to a table with an identity column and three "normal" columns using entity framework in wpf.
however i got this error message:
Cannot insert explicit value for identity column in table 'MyTable' when IDENTITY_INSERT is set to OFF
here is my code snippet, trying to add to the user table who has name, surname, age and userID(identity) column:
var newuser = new User();
newuser.SurName = surNameTextBox.Text;
newuser.Name = nameTextBox.Text;
newuser.Age = Int32.Parse(ageTextBox.Text);
context.AddToUsers(newuser);
context.SaveChanges();
Can anyone help me on solving this problem?
I'm not familiar with entity-framework, but for the curious this is the MS SQL command for enabling an insert on an identity column:
SET IDENTITY_INSERT tablename ON
I agree with Wonko to Sane, the problem is almost certainly in the AddToUsers method.
Identity columns indeed update themselves - that is their purpose.
If this is the only code that you are using to update the User, then I would look at (or post) the AddToUsers method in the DataContext.