Solved

How to create custom ID generator for Entity Framework?

Posted on 2013-05-11
2
2,776 Views
Last Modified: 2013-05-16
How can I create a custom ID generator for Entity Framework to use a unique string for a primary key?

My client has a requirement that all tables must contain a primary key of a GUID but to be stored as a CHAR(32) without dashes for braces.  Currently, I am having to manually stuff the PK values manually while instantiating entities and/or adding them to collections.  I would really like for Entity Framework to call a small piece of custom logic to create the primary key AND have this generator available in the Designer for model-first design:

id = Guid.NewGuid().Replace("-", "").Replace("{", "").Replace("}", "");

Open in new window

0
Comment
Question by:MrNMrsGeek
2 Comments
 
LVL 42

Accepted Solution

by:
sedgwick earned 500 total points
ID: 39159198
the following posts explained it:
http://stackoverflow.com/questions/5275306/does-entity-framework-4-code-first-have-support-for-identity-generators-like-nhi
http://stackoverflow.com/questions/5643620/assigning-ids-to-entities-with-entityframework-4

basiaclly, u override OnModelCreating and call HasDatabaseGeneratedOption() with HasDatabaseGeneratedOption.None to disable auto ID generation.
then u override SaveChanges() and use your generation code for the identity column:
public override int SaveChanges()
    {
        foreach (var entry in ChangeTracker.Entries<MyEntity>()
            .Where(e => e.State == EntityState.Added))
        {
            entry.Entity.Id = Guid.NewGuid().Replace("-", "").Replace("{", "").Replace("}", "");
        }

        return base.SaveChanges();
    }
}

Open in new window

0
 

Author Closing Comment

by:MrNMrsGeek
ID: 39172313
Not exactly a generator.  Not exactly what I wanted.  However, this works, I guess.  I was specifically looking for a generator.  Overriding SaveChanges is a hack in that I must either (a) force all of my types to have the same property, or (b) check the entity type within SaveChanges to find all custom types that have said property, or (c) use Reflection to determine IF the object has the property.  None of these are what I want.  My only reason for awarding this as a solution was because it is not sedgwick's fault.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Both in life and business – not all partnerships are created equal. As the demand for cloud services increases, so do the number of self-proclaimed cloud partners. Asking the right questions up front in the partnership, will enable both parties …

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now