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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With