Deleting Entity with OneToMany Relationship With Another Entity - c#

I have two tables. These are Design and Like. One design can have many likes and one like should be related to one Design.
When I try to delete a Design it throws me an exception:
The DELETE statement conflicted with the REFERENCE constraint
"FK_dbo.DesignLike_dbo.Design_DesignId". The conflict occurred in
database "XXXDB", table "dbo.DesignLike", column 'DesignId'. The
statement has been terminated.
modelBuilder.Entity().HasMany(x => x.Likes).WithRequired(x => x.Design).WillCascadeOnDelete(false);
I dont even try to delete related entities ? Why I get this exception ?

You are trying to delete an object that still has child objects. And the foreign key on the child objects will give you this exception.
You should decouple the child objects are link them to another parent before deleting the current one. Or include them in a cascaded delete.
In your case the design you are trying to delete has at least one like with the foreign key set to the id of your design. When you now delete the design and cascading is off it will violate the foreign key constraint of your like.

It sounds like you've set up your database to enforce a valid foreign key constraint on the DesignId column in your DesignLike table.
If you try and delete a Design, you're deleting the DesignId which is referenced by all the DesignLikes as a foreign key. If you were allowed to do that, you'd find your database in an inconsistent state - your foreign key wouldn't really have meaning if there isn't a guarantee it references a valid record.
You could either remove the now invalid foreign key from your child objects, or set add a Deleted / Visible flag to your Design if you wish keep the Design and corresponding DesignLikes

Related

The UPDATE statement conflicted with the FOREIGN KEY constraint when foreign key value is untouched

I am using SQL through C# to make an update to a row in a table as shown below
context.AssessmentInvitation.Attach(assessmentInvitation);
context.Entry(assessmentInvitation).State = EntityState.Modified;
await context.SaveChangesAsync();
When this is executed in some cases, I get an exception on SaveChangesAsync due to a foreign key constraint. The foreign key constraint has to do with a CompanyId as part of the assessmentInvitation object being updated. This constraint is set to cascade on update, which seems to be the common solution to this issue. This did not resolve the issue for me.
The interesting thing is that the update causing this issue is not touching this foreign key at all. It is only updating a BIT to set it to true. No other values are being modified. The BIT is not related to any other table in any way, it is not part of any type of key.
Why would this foreign key constraint be relevant to the update at all if it is remaining the same? How can I fix this issue?
edit: The problem was much more simple than I thought. It was using a stored procedure that was not fetching the entire AssessmentInvitation object. Actually, it excluded the CompanyId completely. So when I tried to update without the existing CompanyId, obviously it failed. I thought I was going to learn something about Entity Framework, instead I realized I'm not very good at going through other people's code.
I can't add a comment so I'm posting an answer hope it helps you,
try to inspect the properties of assessmentInvitation to see if it holds a correct companyId value, if you are creating the object or created by the model binder in request it may has it's CompanyId set to null.

EF6 Table Splitting with foreign keys (Database first)

I'm currently investigating the possibility to use table splitting with EF to stop pulling too many columns for nothing. As for now, I'm able to create a new entity, cut/paste the fields into the sub-entity and map it without much problems.
However, if one of those fields is a FK in the master table, it gives me the following error
"Running transformation: There is no property with name 'IdDocumentImportSource' defined in type referred by Role 'DocumentImports'."
I do understand that the both tables have a NavigationProperties that cannot be resolved anymore by the association FK because the field has been moved to the child table.
Here's my question; Is there a way to automaticaly move the association FK to the child table? I could only make it work by manually deleting the association, both navigation properties, creation the association FK of the child. It involves quite a lot of work on my part if I have to do all this manually for every association FK I got...!
DocumentImports is the ParentTable that I splitted into a new child table DocumentImports_StatusDetail and DocumentImportSources is the table being referenced by the FK.
Thanks!

Code first of EF, how to define navigation property relationship without setting foreign key between table in database

I use code first of Entity framework. There are two classes "Question" and "User". I defined a relationship as below:
this.HasRequired(v => v.Creator).WithMany(v => v.Questiones)
.HasForeignKey(v => v.CreatorId).WillCascadeOnDelete(false);
After gernerating the database I found that it always create foreign key between Id of User and CreatorId of Question. Because of lower performance of FK(and other reason),I want to define navigation property relationship without setting foreign key in database? Delete FK after EF created it?
If cannot do this using fluent api, could you tell me why EF designed in this way please?
About the lower performance of FK. I have a User table with 5 Million records in it. when I insert a Question into db, since the db check the question.CreatorId validation from User table, it always slower than without FK.
And there are many other reasons that I need to remove FK.
I think I am somewhat obsession because I think that deleting FK after created it is strangely and ugly. What i want is implementing this by using something like WithoutForeignKey in fluent api:
this.HasRequired(v => v.Creator).WithMany(v => v.Questiones)
.WithoutForeignKey(v => v.CreatorId).WillCascadeOnDelete(false);
Without questioning why are you trying to do this strange thing and going just to the answer: you could delete fk constraint after generated, or you could use migrations and remove FK generation from the migration code.
SQL code generated when traversing nav properties will work even if fk constraint doesn't exist, except for cascade deleting
If you want a relationship between two tables, you need to define a foreign key. No way around it. Even if you use Map() in fluent api, you can only hide the foreign key in your model, in the background EF will still use it and it will exist in the database.
Also I don't get what you mean by "performance" of foreign key? One extra (likely small) column won't make a difference. If you mean the navigation properties for the performance part, you can do 3 things:
Don't include them in your model
Make them non-virtual to disable lazy loading
Disable lazy loading all together with ctx.Configuration.LazyLoadingEnabled = false;
If you don't want to tell db about relation and treat both entities as not related (I wonder why), then just ignore these navigation properties and FK field. Note that you will be responsible for managing related entities: saving and loading them from db, updating ids etc
this.Ignore(q => q.Creator);
this.Ignore(q => q.CreatorId);
And you also need to ignore other side of relation, otherwise EF will generate FK column with default name Creator_CreatorId. So in Creator entity configuration:
this.Ignore(c => c.Questiones);

Save entity in Entity Framework without a primary key

Scenario:
Database first.
I have a table with no primary key set and I'm trying to make an update with Entity Framework.
This is the error message I keep getting:
The property 'inactive_date' is part of the object's key information and cannot be modified.
If I set the fields 'Entity Key' value to 'false' I get this error messge:
Modifications to tables where a primary key column has property 'StoreGeneratedPattern' set to 'Computed' are not supported. Use 'Identity' pattern instead. Key column: 'timestamp'. Table: 'plat12Model.Store.glchart'.
Would this be corrected if I created a primary key? Can I set a primary key in my code rather than on the database?
By default, EF will make tables without primary keys and views into read-only classes where every field is part of the composite key. You can modify the conceptual model to reflect the actual behavior as long as you retain a key value that EF will use for object tracking. As the error message states, you also need to make the columns no longer computed in order to update them as well.

Features in C# for SQLCE foreign keys

I know how to do SQL query to add foreign keys, connect to DataBase and fetch data in C# and such. But after long hours searching on Google, I cannot find any features (or classes, methods, API etc.) in C# that has anything to do with Foreign Key.
Back when I was in Rails, if two tables has relationship I can easily access a child table through the parent table by Teacher[0].Classes.Last . But these methods seems to be missing in C#? Am I right?
I'm working with C#, SQLCE and WPF.
I have two tables that has one-to-one relationship. But all the data including the reference key are inserted manually (e.g. this row, insert a "1", that row insert a "5" etc.) and to find a rows in the child table corresponding to a parent table's ID, I just have to do an if statement in C#.
So basically a Foreign Key to me is just another int column. I don't get what the reference actually does or is it just a naming convention? Just so reader of the code sees a reference and recongnize there is a relation, but the foreign key doesn't actually do anything substantially?
Back when I was in Rails, if two tables has relationship I can easily access a child table through the parent table by Teacher[0].Classes.Last, But these methods seems to be missing in C#?
You can do something similar with Entity Framework and many other ORMs out there.
So basically a Foreign Key to me is just another int column. ... Just so reader of the code sees a reference and recongnize there is a relation, but the foreign key doesn't actually do anything substantially?
Correct - the value of the foriegn key loses significance once you leave the database. Instead what is normal is to have nested objects. For example, you can have a Customer object which can contain an Address object. The Address object may also carry around its foriegn key value, but generally you wouldn't use it in the C# code (unless you were doing something like a LINQ query with it) - you would use the foriegn key value once you got back to the database.
A foreign key represents a relationship between objects in your Domain model. It enforces integrity.
(In some databases, foreign keys can also speed up queries because the query optimiser is able to make use of this information)

Categories

Resources