Reputation: 7804
I was wondering (and I hate using the words 'Best Practice') - but is this a good way to approach configuration as it encapsulates the config for AAA?
I see a lot of examples where the OnModelCreating
is a huge list of instructions for creating the database and long methods tell me something isn't quiet right.
public class MyContext : DbContext
{
public MyContext() : base("name=MyDb") { }
public DbSet<AAA> AAAs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Configurations.Add(new AAA.Configuration());
}
}
And the class with a spot for it's config
public class AAA
{
[Key]
public int Id { get; set; }
[Required]
public string Details { get; set; }
internal class Configuration : EntityTypeConfiguration<AAA>
{
public Configuration()
{
// Set all the funky stuff here
}
}
}
I get that there probably isn't one right way. Before I commit a lot of time and tears I am looking for a reason why this might be absolutely the worst idea in the world or if there is a way to do something similar?
EDIT
A Colleague suggested this as an alternate method using a static property
public class AAA
{
[Key]
public int Id { get; set; }
[Required]
public string Details { get; set; }
public static EntityTypeConfiguration<AAA> Configuration
{
get { return new AAAConfiguration(); }
}
}
internal class AAAConfiguration : EntityTypeConfiguration<AAA>
{
public AAAConfiguration()
{
// Set all the funky stuff here
}
}
I like this as it gives me a bit more flexibility with how the configuration is instanced.
Upvotes: 1
Views: 970
Reputation: 6239
I personally don't see an issue in the approach you have taken. I have just recently resolved a similar dilema in my head, the only difference being is I have the EntityTypeConfiguration<T>
classes inside my data layer and not within my model. I'm doing all the mapping logic in these mapping classes too; this means I don't have to decorate my model with EF specific attributes, keeping them totally persistence-ignorant.
With your approach, in the OnModelCreating
method you only need to have one line per class that you want to persist, plus this code is only hit once if you don't clear the cache that EF creates, so it's only a kind of one-off bootstrap and therefore a long method isn't an issue?
I think your approach is fine, but I'm sure there will be some differing views on the subject.
Upvotes: 2
Reputation: 62093
It depends. I am by now far enough to say that I don't care about db generation. It is nice and has advantages (platform independent) which I do not care about. it is limiting from using SQL Server fully - so it is back to database projects.
This is a world of compromises, and - sorry- a best practice comes with a TON of limitations there.
Upvotes: 3