1. 生成數(shù)據(jù)庫字段:
1.1 字段的最大長(zhǎng)度:
public PersonConfig()
{
this.ToTable("T_Persons");
this.HasKey(p => p.Id)//主鍵
this.Ignore(p => p.Name1);//某個(gè)字段不參與映射數(shù)據(jù)庫
this.Property(p => p.Name).IsFixedLength()//是否對(duì)應(yīng)固定長(zhǎng)度
this.Property(p => p.Name).IsUnicode(false)//對(duì)應(yīng)的數(shù)據(jù)庫類型是 varchar 類型案怯,而不是nvarchar
this.Property(p => p.Id).HasColumnName("Id")//Id 列對(duì)應(yīng)數(shù)據(jù)庫中名字為 Id 的字段
this.Property(p =>p.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)//指定字段是自動(dòng)增長(zhǎng)類型
this.Property(p => p.Name).IsRequired() //屬性不能為空
this.Property(p => p.Name).HasMaxLength(50);//長(zhǎng)度為 50
this.Property(p => p.Name).IsOptional() //屬性可以為空
}
1.2 查看異常(DbEntityValidationException ):
try
{
tdc.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var err in ex.EntityValidationErrors)
{
foreach (var item in err.ValidationErrors)
{
Console.WriteLine("錯(cuò)誤:"+item.PropertyName+"信息:"+item.ErrorMessage);
}
}
}
另一種寫法:
try
{
ctx.SaveChanges();
}
catch(DbEntityValidationException ex)
{
StringBuilder sb = new StringBuilder();
foreach(var ve in ex.EntityValidationErrors.SelectMany(eve=>eve.ValidationErrors))
{
sb.AppendLine(ve.PropertyName+":"+ve.ErrorMessage);
}
Console.WriteLine(sb);
}