Prevent set null on delete in Entity Framework database-first - c#

I have a database-first model using Entity Framework 6.2.0 which has the following association:
As you see, the OnDelete property on both ends is set to None. The corresponding relation in SQL server is shown below:
Although there is no explicit setting to set null on delete, when I try to remove an object from Plannings (primary table), EF sets all foreign key records in the table Waybill to null.
In the same database and model, I have the following foreign key and corresponding association:
All circumstances are the same as earlier. But in this case, when I try to remove an object from Products, it fails because of conflict with foreign key constraint (as I expect).
Why these two similar cases have different behavior? How can I completely disable set null on delete in my database-first model? I know that in code-first model, we can delete conventions using the following:
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
But I could not find any way to do this in database-first.

Related

Entity Framework Extensions: Can't BulkMerge entities with empty identity property

I uses BulkMerge method of Entity Framework Extensions for insert/update large collections of entities. Entity table have identity column Id that used as a primary key. When I try to BulkMerge collection with several newly created entities (they have Id = 0 by default) it throws such exception: Violation of PRIMARY KEY constraint 'PK_Users'. Cannot insert duplicate key in object 'dbo.Users'. The duplicate key value is (0). Btw, BulkInsert method with same entities works fine. I tried to use options like AutoMapOutputDirection, InsertIfNotExists or MergeKeepIdentity but they were ineffective. Can anyone suggest the correct options for proper BulkMerge work or any other ways to solve issue?

EF Foreign Key Associations Deleted

The picture show relation with two tables in my database;
Well as you can see there's a field called "DeviceTypeID" in the right side table.
Normally EF adds CompanyTypeID column to the ServiceLaburDefinitions model but it's disappeared last time I updated model from the database.
I am searching for a solution for a couple of hours but not able to find any solution. Could anyne suggest a solution?
Thanks.
ServiceLaburDefinitions is the depend entity and has the DeviceTypeID foreign key property defined.
So Entity Framework creates a navigation Key under the hood between the 2 tables based on DeviceTypeId key.
You can see for example how a navigation key is created also in the following example between the foreign key and the primary key
More information about navigation properties can be found here
When you create the model from the database, there is a checkbox marked "Include Foreign Key columns In The Model" - Make sure this is checked.

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

Entity Framework read entity properties in SaveChanges

I am using Entity Framework 5 code-first and I have overridden the SaveChanges method. In SaveChanges, I want to identify any entities with an EntityState == EntityState.Added (I can do this easily enough) however I then want to identify any columns in those entities which have been defined as a primary key, have their HasDatabaseGeneratedOption property set to DatabaseGeneratedOption.None and currently have Null value.
I need to identify these columns as my database currently has some columns defined as primary keys which need to be manually populated via code. I figured I could tackle this population of columns in SaveChanges on an insert but am stumped as to how to identify them.
How do I query column definitions in SaveChanges? I obviously know how to examine the data value
You need to look at the data model, get the property that holds the primary key and see if it has the attribute you want. See an example here: http://weblogs.asp.net/ricardoperes/entity-framework-metadata.
However, this will not work if you are not using attributes, but instead customizing the model in OnModelCreating.

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.

Categories

Resources