Aug 23, 2013 Making a temporary ID for entities in EF before saving. Ask Question 0. (many-many relationship) in the third table. Before saving the items all Ids in the first two tables will be set to 0, when adding items to the relation table I have no problems, the problems comes when saving the tables because the relationship table will have the. Entity Framework - set ID of new object manually. In some instances it is important for the object IDs to remain the same in the new database as they are in the old one. Normally when you create a new object and call context.SaveChanges it will automatically assign an identity value to the ID column.
ModelBuilder.Entity.HasRequired(e = e.Parameters).WithRequiredDependent(p = p.Company). Has turned Company into a dependent entity, which means that it no longer creates its own primary key, but it waits for Parameters to get a primary key and then takes that value for its own primary key (which is a foreign key at the same time).I think in your case, this mechanism is hampered somewhat by Parameters.CompanyId so EF ends up inserting 0 for Company.Id. But that doesn't really matter, because you should turn it aroung: Parameters should be the dependent entity: modelBuilder.Entity.HasRequired(e = e.Parameters).WithRequiredPrincipal(p = p.Company);Now Parameters will have a primary key that's also a foreign key (to Company), making Parameters.CompanyId redundant.By the way, using plural names for classes is confusing.
I’ve already covered the practical advantage of the code-first approach featured by Entity Framework 6: the key concept there was all about creating the whole data model starting from some very standard C# classes: namely, the Entities. The most frequent question asked by readers was: how to define an auto-increment Id field (or primary key) of an Entity? In other words, how can we tell the DB to assign an unique, incremental id number to each and every record by its own?The answer is quite simple, as long as you’re using, or any other Entity Framework compatible DBMS featuring a native auto-incremental numeric fields support: all we can do is to tell the Entity Framework to properly generate it.In order to do so we just need to use the DatabaseGeneratedAttribute in the following way.