Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning ids to entities with EntityFramework 4

I'd like to implement "default" Id generation support for my entities.

When saving the entity, I'd like EntityFramework to only generate the id value for the Entity if it's not already set. If the ID already has a non-null, non-zero value, I want to have that entity ID preserved when the entity is saved in the database.

I'm migrating data from a legacy data model (EntityFramework model created from the old database) to a newly created (model-first) EntityFramework model. Let's call the old model A, and the new model T.

Typically, I'd want T entities to get their Ids set upon save (they're all int64), for the long-term use of the new model.

Currently, I'm explicitly assigning T entity Ids based on the Id of the corresponding A entity from which I'm migrating. This is so the migration results are easy to check.

However, although I can assign the id for a T entity to the same id as the A entity in my migration routine, after I save the entities the Id values have changed.

Is there a way to override the default saving method for all entities in the T model so the id value is only assigned if it's not already set in the entity before it gets saved?

I've looked at some of the other EntityFramework/Id questions here, but to my mind none of them are asking the same thing.

Thanks for any leads.

like image 892
John Kaster Avatar asked Apr 13 '11 01:04

John Kaster


People also ask

How do I get my ID after SaveChanges?

Now, when you add a new Student and call SaveChanges() method, EF will assign a newly generated id to the StudentID property. EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope.

What is DbContext and DbSet in Entity Framework?

DbContext generally represents a database connection and a set of tables. DbSet is used to represent a table. Your code sample doesn't fit the expected pattern.

What is EDMX in Entity Framework?

An . edmx file is an XML file that defines an Entity Data Model (EDM), describes the target database schema, and defines the mapping between the EDM and the database. An . edmx file also contains information that is used by the ADO.NET Entity Data Model Designer (Entity Designer) to render a model graphically.

How do I use code first in Entity Framework?

Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…


2 Answers

I see you mentioned that you are using Model First. However, I have a Code First sample that may be of some help.

On the T entity, you have a [Key] attribute on the id property, no? If so, you can use another attribute, DatabaseGeneratedAttribute, to force the identity to be set.

public class SomeEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int? SomeEntityID { get; set; }
}

Also, there is a Fluent API call to achieve a similar result:

public class YourContext : DbContext
{
    protected override void OnModelCreating( DbModelBuilder dbModelBuilder )
    {
        base.OnModelCreating( dbModelBuilder );

        var config = dbModelBuilder.Entity<SomeEntity>();
        config.Property(e => e.SomeEntityID).HasDatabaseGeneratedOption( DatabaseGeneratedOption.None);
    }
}
like image 140
Ed Chapel Avatar answered Sep 30 '22 19:09

Ed Chapel


After continued searching, reading, and discussions with some friends who know more about EF than I currently do, I think the only practical, sustainable way to achieve what I'm looking for with the current Entity Framework implementation is to create a custom Entity Framework provider, as discussed in this blog post.

Whether or not I'll have the time to implement this is something I'll have to figure out, but I thought I'd at least wrap up this answer. A custom provider would also allow one to implement decrypt on read/encrypt on write attributes for the entities as well.

These features are both things I hope to see baked in to a future release of EntityFramework, though.

like image 36
John Kaster Avatar answered Sep 30 '22 18:09

John Kaster