Reputation: 10509
I want to implement a base class for my entities, so I don't have to define a Guid Id field in each entitiy. I have created the following base class:
public abstract class IdableEntity
{
[Key]
public Guid Id { get; set; }
protected IdableEntity()
{
Id = Guid.NewGuid();
}
}
This is done becuase as far as I know I can just use [DatabaseGenerated...] attribute in this case, since I would have to go to a database and alter all the table's ID field to have (newid()) call as an "initializer". This is very inconvenient if one has many entity classes - therefore many tables.
But now, I will have to decleare a constructor with a call to base constructor in each child class, right? If so, does it even worth it?
Upvotes: 0
Views: 506
Reputation: 24410
An alternate solution to your problem is to use code to automatically go through all your tables and setup the default constraint. Someone else has already answered how to do that here: SQL Server - Add default constraints to all tables
Upvotes: 0
Reputation: 9837
If you use your code the way it is, all you'll need to do is this:
public class ChildEntity : IdableEntity
{
// ...
}
When you create instances of the ChildEntity class, the protected base IdableEntity constructor will automatically be called because it takes no parameters.
Upvotes: 2