Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 520
Dan McClain Avatar asked Jul 24 '09 13:07

Dan McClain


People also ask

Is it good to use GUID as primary key?

Having a guid column is perfectly ok like any varchar column as long as you do not use it as PK part and in general as a key column to join tables. Your database must have its own PK elements, filtering and joining data using them - filtering also by a GUID afterwards is perfectly ok.

What is GUID in EF core?

GUID primary keys are usually required, when you need meaningful primary keys before inserting data in database (e.g., there are client apps, that later synchronize data with main database). In other words, the only advantage from GUID PK is ability to generate it at client side.

Is GUID auto generated?

For example, on SQL Server, when a GUID property is configured as value generated on add, the provider automatically performs value generation client-side, using an algorithm to generate optimal sequential GUID values.

What is the difference between EF6 and EF core?

Guidance for existing EF6 applicationsKeep using EF6 if the data access code is stable and not likely to evolve or need new features. Port to EF Core if the data access code is evolving or if the app needs new features only available in EF Core. Porting to EF Core is also often done for performance.


1 Answers

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

like image 167
Alex James Avatar answered Oct 16 '22 13:10

Alex James