使用 IEntityTypeConfiguration 将列类型设置为 NCHAR 而不是 NVARCHAR
Set column type to NCHAR instead of NVARCHAR with IEntityTypeConfiguration
我正在使用 EF Core 2。2.x 并且 table 有 50 多个字符串列。在我的迁移中,我想将所有这些设置为 NCHAR
而不是 NVARCHAR
。它们都有不同的长度。有没有办法同时更改所有列的 SQL 类型,而无需在每一列上手动设置它?我想在我的 IEntityTypeConfiguration
.
中执行此操作
public class MyTableConfig : IEntityTypeConfiguration<MyTable>
{
public void Configure(EntityTypeBuilder<MyTable> entity)
{
foreach (var property in entity.Metadata.GetProperties()
.Where(p => p.ClrType == typeof(string)))
{
if (property.GetMaxLength() == null)
property.SetMaxLength(256);
// Can it be set from here?
}
entity.ToTable("MyTable", "fooSchema");
entity.Property(e => e.Address1).HasMaxLength(30);
entity.Property(e => e.Address2).HasMaxLength(20);
/* A lot of other declarations below */
}
}
我知道我可以使用 IsFixedLength
,但我想在所有列上使用它。
在 EF 2.x 中,您可以使用 IsFixedLength property of the RelationalPropertyAnnotations class returned by Relational 扩展方法,而不是 IsFixedLength
流畅 API:
property.Relational().IsFixedLength = true;
在 EF Core 3.0+ 中,使用 SetIsFixedLength 扩展方法实现了同样的效果:
property.SetIsFixedLength(true);
public void Configure(EntityTypeBuilder<MyTable> entity)
{
foreach (var pb in entity.Metadata.GetProperties()
.Where(p => p.ClrType == typeof(string))
.Select(p =>
new
{
PropertyBuilder = entity.Property(p.Name),
Property = p
}))
{
int length = pb.Property.GetMaxLength() ?? 256;
pb.PropertyBuilder.HasColumnType($"NCHAR({length})");
}
}
我正在使用 EF Core 2。2.x 并且 table 有 50 多个字符串列。在我的迁移中,我想将所有这些设置为 NCHAR
而不是 NVARCHAR
。它们都有不同的长度。有没有办法同时更改所有列的 SQL 类型,而无需在每一列上手动设置它?我想在我的 IEntityTypeConfiguration
.
public class MyTableConfig : IEntityTypeConfiguration<MyTable>
{
public void Configure(EntityTypeBuilder<MyTable> entity)
{
foreach (var property in entity.Metadata.GetProperties()
.Where(p => p.ClrType == typeof(string)))
{
if (property.GetMaxLength() == null)
property.SetMaxLength(256);
// Can it be set from here?
}
entity.ToTable("MyTable", "fooSchema");
entity.Property(e => e.Address1).HasMaxLength(30);
entity.Property(e => e.Address2).HasMaxLength(20);
/* A lot of other declarations below */
}
}
我知道我可以使用 IsFixedLength
,但我想在所有列上使用它。
在 EF 2.x 中,您可以使用 IsFixedLength property of the RelationalPropertyAnnotations class returned by Relational 扩展方法,而不是 IsFixedLength
流畅 API:
property.Relational().IsFixedLength = true;
在 EF Core 3.0+ 中,使用 SetIsFixedLength 扩展方法实现了同样的效果:
property.SetIsFixedLength(true);
public void Configure(EntityTypeBuilder<MyTable> entity)
{
foreach (var pb in entity.Metadata.GetProperties()
.Where(p => p.ClrType == typeof(string))
.Select(p =>
new
{
PropertyBuilder = entity.Property(p.Name),
Property = p
}))
{
int length = pb.Property.GetMaxLength() ?? 256;
pb.PropertyBuilder.HasColumnType($"NCHAR({length})");
}
}