I am working on .net core 6 along with EF-Core 7. I have define config class for the model where I have define HasMaxLength
. When I run migration on ef core, it ignore the string length. I have also tried with .HasColumnType("nvarchar(80)
but still no luck; not sure what I missing here?
Incorrect length based on config
migrationBuilder.CreateTable(
name: "JobProfiles",
columns: table => new
{
JobProfileId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
SourceServer = table.Column<string>(type: "nvarchar(max)", nullable: false),
SourceDirectory = table.Column<string>(type: "nvarchar(max)", nullable: false),
DestinationServer = table.Column<string>(type: "nvarchar(max)", nullable: false),
DestinationDirectory = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
Model
public class JobProfile
{
public Guid JobProfileId { get; set; }
public string Name { get; set; }
public string SourceServer { get; set; }
public string SourceDirectory { get; set; }
public string DestinationServer { get; set; }
public string DestinationDirectory { get; set; }
}
Config
public class JobProfileConfiguration : IEntityTypeConfiguration<JobProfile>
{
public void Configure(EntityTypeBuilder<JobProfile> builder)
{
builder.ToTable("JobProfile", "dbo");
builder.HasKey(column => column.JobProfileId);
builder.Property(c => c.Name)
.IsRequired()
.HasColumnType("nvarchar(80)");
builder.Property(c => c.SourceServer)
.IsRequired()
.HasMaxLength(350);
builder.Property(c => c.SourceDirectory)
.IsRequired()
.HasColumnType("nvarchar(max)");
builder.Property(c => c.DestinationServer)
.IsRequired()
.HasMaxLength(350);
}
}
CodePudding user response:
Try this
[Table("JobProfile")]
public class JobProfile
{
[Key]
public Guid JobProfileId { get; set; }
[Required]
public string Name { get; set; }
[MaxLength(350)]
[Required]
public string SourceServer { get; set; }
[Required]
public string SourceDirectory { get; set; }
[MaxLength(350)]
[Required]
public string DestinationServer { get; set; }
public string DestinationDirectory { get; set; }
}
You could also add more annotations which is neater than configure it inside the builder in my opinion
CodePudding user response:
You can use annotation in dotnet like this -
Column annotation can be used in multiple purpose. It's one of them.
[Column(TypeName = "nvarchar(max)")]
public string SourceDirectory { get; set; }
You can also use fluent api -
builder.Property(obj => obj.SourceDirectory.IsMaxLength());