开发者

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 h开发者_运维技巧ave 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜