I created a simple code first entity for learn purpose. Does EF6 automatically select the property to auto-increment? Because I found that it appears to be doing this. Does it automatically select the primary key too?
My search on this question yielded answers to questions of how to switch the identity property using "Data Annotations" Source but that doesn't exactly answer my question.
Does EF6 automatically select the property to auto-increment?
What you are describing is an Identity column (auto increments) which is also a primary key.
So let's visit the documentation:
Code First Data Annotations
Entity Framework relies on every entity having a key value that is
used for entity tracking. One convention of Code First is implicit key
properties; Code First will look for a property named “Id”, or a
combination of class name and “Id”, such as “BlogId”. This property
will map to a primary key column in the database.
Note : the key will also be defined as Identity by default
There is a lot more to this and various ways to configure fields and tables, so I recommend reading the documentation thoroughly.
Related
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.
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.
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);
I'm using the code-first approach and because of that I do not have the .edmx file so I cannot change the StoreGeneratedPattern attribute. How do I then make EF auto-increment the IDs? (right now all IDs are zeros by default)
A primary key with auto-increment (default behavior) is generated if any of the following holds true:
The class contains a property named "Id"
The class contains a property named $className + "Id"
The property of interest is annotated with KeyAttribute
Might it be that your property is named "ID" instead of "Id" without the Key attribute?
There are three ways to specify keys using EF code first:
Use built-in code conventions (his first two bullets)
Use the KeyAttribute data annotation directly on the property/field
Use the Fluent API to specify the key field
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.