Home > Software engineering >  EF Core: combining 2 configuration extension method calls in one extension method call
EF Core: combining 2 configuration extension method calls in one extension method call

Time:10-02

I am using EF Core Code-First Approach to configure/map an entity class named Student to SQL Server table named Student. The Student entity model class has a string column named Name that will be mapped to a SQL Server column named "Name" that belongs to nvarchar and has maximum length of 50.

Currently, to get what I configure for the Name column, I call 2 extension methods that are HasMaxLength() and HasColumnType():

builder.Property(s => s.Name).IsRequired(true).HasMaxLength(50).HasColumnType("nvarchar");

My question: I'd like to combine those 2 extension methods to 1 extension method HasColumnType() as follows. But I am not sure that works or not. Please help.

 builder.Property(s => s.Name).IsRequired(true).HasColumnType("nvarchar(50)");

Details of my Student entity/column configuration class:

public class StudentConfiguration: IEntityTypeConfiguration<Student>
    {
        public void Configure(EntityTypeBuilder<Student> builder)
        {
            
            // 1) Table
            builder.ToTable("Student");

            // 2) Key
            builder.HasKey(s => s.StudentId);
            builder.Property(s => s.StudentId).UseIdentityColumn(1, 1);

            // 2) Properties
            builder.Property(s => s.Name).IsRequired(true).HasMaxLength(50).HasColumnType("nvarchar");
            ...


            ...
        }
    }

And my Student entity class:

public class Student
    {
        public long StudentId { get; set; }
        public string Name { get; set; }
        public int? Age { get; set; }
        public bool IsRegularStudent { get; set; }
       
    }

CodePudding user response:

That would work,I tried as you mentioned

enter image description here

but if you pass a wrong data type parameter into this method,you would get the error when you update database:

Column, parameter, or variable #2: Cannot find data type xx.
  • Related