3

I am studying EF Core with database first. There is no issue to get entities and DbContext after reverse-engineering. But I couldn't understand the role(or purpose) OnModelCreating Method in DbContext(database first approach). Here is code snippet.

public partial class VitiLevuContext : DbContext
{ 
    public virtual DbSet<Order> Orders { get; set; }
    public virtual DbSet<Invoice> Invoices { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Invoice>(entity =>
        {
            entity.ToTable("Invoice");
            entity.Property(e => e.DueAmount)
            .IsRequired();
            entity.Property(e => e.PaidAmount).HasColumnType("money");
            entity.HasOne(d => d.Order)
                .WithMany(p => p.Invoices)
                .OnDelete(DeleteBehavior.Cascade)
                .HasForeignKey(d => d.OrderId)
                .HasConstraintName("FK__Invoice__OrderId__44FF419A");
        });
        modelBuilder.Entity<Order>(entity =>
        {
            entity.ToTable("Order");
        });
        OnModelCreatingPartial(modelBuilder);
    }
    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

Database has a relation and "NOT NULL Contraints".

  1. ALTER TABLE [dbo].[Invoice] ADD FOREIGN KEY ([OrderId]) REFERENCES [dbo].Order ON DELETE CASCADE.
  2. ALTER TABLE [dbo].[Invoice] ADD [DueAmount] int NOT NULL

The OnModelCreating method represents well. I created very simple Rest API project and tested add/delete for Order/Invoice. "NOT NULL Constraints" and "Cascade deleting" may be verified on database not EF model side. (In case of creating an invoice instance with null DueAmount, I expected exceptions before submitting to SQL)

My question is very simple. Can I delete "OnModelCreating" method if don't consider migration? (I thought the OnModelCreating method is only for migration purpose.)

0

1 Answer 1

8

If you follow the Entity Framework's model naming conventions and your model directly reflects your database table names and column names, you don't need to use the OnModelCreating method. This is because Entity Framework will generate the necessary bindings behind the scenes.

However, if you want customization—for example, if your model field name does not match your database table column name—you configure that using the OnModelCreating method. Another way of using this configuration is called the Fluent API.

This doesn't mean you have to use the OnModelCreating method; there are other options for customization, such as Data Annotations.

For example:

If you have a model named User:

public class User
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public string Password { get; set; }
}

In your DbContext, you set the following:

public class AppDbContext : DbContext
{
   public AppDbContext(DbContextOptions<AppDbContext> options) {}

   public DbSet<User> Users { get; set; }
}

So, by convention, Entity Framework expects:

  1. A table named Users, because of the name you used on the DbSet property for the User model.
  2. It uses Id as the primary key because the model property is named Id.

Entity Framework will set this up for you.

When we come to custom configuration, let's say your model property name Password is not the same as the Users table column name Pwd. You have to tell Entity Framework in one of the following ways:

  1. Using the OnModelCreating method (Fluent API):

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>(entity => {
             entity.Property(p => p.Password)
                   .HasColumnName("Pwd");
        });
    }
    
  2. The other way is using Data Annotations:

    public class User
    {
        public int Id { get; set; }
        public string FullName { get; set; }
    
        [Column("Pwd")]
        public string Password { get; set; }
    }
    
Sign up to request clarification or add additional context in comments.

1 Comment

it is what I want to know. "If you follow the Entity framework model naming convention and your model directly reflects your database table name, column names and so on, you don't need the OnMOdelCreating method. This is because the entity framework will generate the code behind the scene."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.