Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i use override OnModelCreating method with DB first

Tags:

c#

asp.net-mvc

I'm trying to integrate asp.net identity to my existing project i'm working with Database first, i am NOT using edmx to generate the models and context class, i am creating the models on my own,

Now my question: can i use the "override OnModelCreating" method in the DbContext class OR is it only usable for code first approach

like image 698
Hershy D Avatar asked Oct 21 '25 06:10

Hershy D


1 Answers

Yes, you absolutely can. The DbContext is, after all, just an object-oriented-model of your data. If a generator scaffolded that out for you or if you hand crafted it manually, is of no concern. I am going down that route myself. The database already exists and is maintained through a .sqlproj project and while it started as code first, I switched around halfway through.

As a practical example. I am using OnModelCreating, to configure my entities:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        //extracted m:n mapping for demonstration puporses
        builder.Entity<AppUserRole>(userRole =>
        {
            userRole.HasKey(ur => new { ur.UserId, ur.RoleId });
            userRole.HasOne(ur => ur.Role)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.RoleId)
                .IsRequired();

            userRole.HasOne(ur => ur.User)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.UserId)
                .IsRequired();
        });

        builder.ApplyConfiguration(new AppUserConfiguration());
        builder.ApplyConfiguration(new MapConfigConfiguration());
        builder.ApplyConfiguration(new MapWidgetConfiguration());
        builder.ApplyConfiguration(new WidgetConfiguration());
        builder.ApplyConfiguration(new LayoutMenuConfiguration());
        builder.ApplyConfiguration(new ImageConfiguration());
        builder.ApplyConfiguration(new FrontPageContentConfiguration());
    }
}

To get started, you can scaffold out the existing database using the Nuget console:

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Foo;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

And then tweak it to your needs, if needed. So if you have json stored in a nvarchar field, add a conversion to automatically map it to a concrete type:

public class LayerConfigurationConfiguration : IEntityTypeConfiguration<LayerConfiguration>
{
    public void Configure(EntityTypeBuilder<LayerConfiguration> builder)
    {
        builder.HasKey(lc => lc.Id);
        /* ... */
        builder.Property(lc => lc.LayerConfig).HasConversion(
            v => JsonConvert.SerializeObject(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }),
            v => JsonConvert.DeserializeObject<LayerConfig>(v)
        );
    }
}

Reference: https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db

like image 98
Marco Avatar answered Oct 23 '25 20:10

Marco