POCOでEntityを定義する際、例えばnvarcharの範囲を超えた文字列としたい、varbinaryの範囲を超えたbyteシーケンスとしたい、又はrowversion/timestampを取得したい場合のメモ。
属性で処理する場合
Attributes.cs
public class AttributeSample
{
[Key]
public int Id { get; set; }
//Size=4000のnvarcharになる。
public string NVarchar { get; set; }
//size=10のncharになる。
[Column(TypeName = "nchar")]
[MaxLength(10)]
public string NChar { get; set; }
//ntextになる。
[Column(TypeName = "ntext")]
public string Text { get; set; }
//Size=4000のvarbinaryになる。
public byte[] VarBinary { get; set; }
//Size=200のbinaryになる。
[Column(TypeName = "binary")]
[MaxLength(200)]
public byte[] Binary { get; set; }
//imageになる。
[Column(TypeName = "image")]
public byte[] Image { get; set; }
//uniqueidentifierになる。
public Guid Uuid { get; set; }
//重複させる必要は無い。何れかを付与すればrowversionになる。
//8byteだからといってlongは指定出来ない。
[Column(TypeName = "rowversion")]
[Timestamp]
public byte[] Rowversion { get; set; }
}
FluentApiで定義する場合
Fluent.cs
public class FluentApiSample
{
[Key]
public int Id { get; set; }
//size=10のncharになる。
public string NChar { get; set; }
//ntextになる。
public string Text { get; set; }
//Size=200のbinaryになる。
public byte[] Binary { get; set; }
//imageになる。
public byte[] Image { get; set; }
//rowversionになる。
//8byteだからといってlongは指定出来ない。
public byte[] Rowversion { get; set; }
}
public class Context : DbContext
{
public Context(string path)
: base(path)
{
}
public IDbSet<AttributeSample> AttributeSamplesSamples { get; set; }
public IDbSet<FluentApiSample> FluentApiSamples { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var entity = modelBuilder.Entity<FluentApiSample>();
//[Column(TypeName = "nchar")]
//[MaxLength(10)]と同じ。
entity.Property(_ => _.NChar).HasColumnType("nchar").HasMaxLength(10);
//[Column(TypeName = "ntext")]と同じ。
entity.Property(_ => _.Text).HasColumnType("ntext");
//[Column(TypeName = "binary")]
//[MaxLength(200)]と同じ。
entity.Property(_ => _.Binary).HasColumnType("binary").HasMaxLength(200);
//[Column(TypeName = "image")]と同じ
entity.Property(_ => _.Image).HasColumnType("image");
//[Column(TypeName = "rowversion")]
//[Timestamp]
//と同じ。
entity.Property(_ => _.Rowversion).HasColumnType("rowversion");
base.OnModelCreating(modelBuilder);
}
}