Dan McClain
Dan McClain

Reputation: 11920

Working with GUIDs and Entity Framework

This question highlights that you can not use server side generated GUIDs with the entity framework. But, I want the generation of the GUID handled at the DAL level of Database API (ie, when an entity's constructor is called, I want the id of the entity to be initialized to a new GUID). My plan is to write a small tool to generate a bunch of code files that are partial classes of the entities. I have a way to do it, the question is: Am I out of my mind for doing it this way or is this the way I should be doing it?

My issue is, when the edmx file is update, I don't want to have to also edit a bunch of code files, I just want to run a tool that will do what is necessary.

Again, Is my head on straight?

Upvotes: 5

Views: 1224

Answers (1)

Alex James
Alex James

Reputation: 20924

Well if you look at the partial classes the Entity Framework generates by default, there is no default constructor.

So doing this in a separate partial class will work nicely:

public partial class Customer{
    public Customer(){
         _ID = Guid.NewGuid();
    }
}

So there is probably no reason not to do something like you are planning.

You might want to look into T4 templates to do this though. That is how EF 4.0 (i.e. EF in .NET 4.0) allows you to customize the generated code. Now while in 4.0 that experience is quite seemless you could easily put something together based on T4 just to create this partials classes that will work just fine in .NET 3.5 SP1.

Hope this helps

Alex

Upvotes: 6

Related Questions