以下是书《Programming Entity Framework Code First》的学习整理,主要是一个整体梳理。

一、模型属性映射约定 

1.通过 System.Component  Model.DataAnnotations 来配置
class AnimalType
{
public int Id { get; set; }
[Required]
public string TypeName { get; set; }
}
意味着TypeName在数据库中的字段为not null。第二个是EntityFramework会对这个模型进行验证。比如在Savechanges的时候,模型的这个属性不能为空,否则会抛出异常。
[Table("Species")]
class AnimalType
{
public int Id { get; set; }
[Required]
public string TypeName { get; set; }
}
像Table这个特性 意味着AnimalType对象在数据库映射到表Species上。
 
2.通过Fluent API来配置模型。
 通过Dbcontext的OnModelCreating来对模型进行配置。
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<AnimalType>().ToTable("Animal");
            modelBuilder.Entity<AnimalType>().Property(p => p.TypeName).IsRequired();
        }
这样得到同样的效果。开发者一般倾向于使用API的方式来约定模型,这样保持class干净,而且API支持映射更多。API在特性后面执行,同样的代码(比如API是.HasMaxLength(300),特性是 [MaxLength(200)],数据库会是300的长度),API会覆盖特性。
如果你有很多属性需要约定,可以单独出来。继承EntityTypeConfiguration。
public class DestinationConfiguration :
EntityTypeConfiguration<Destination>
{
public DestinationConfiguration()
{
Property(d => d.Name).IsRequired();
Property(d => d.Description).HasMaxLength(500);
Property(d => d.Photo).HasColumnType("image");
}
}
public class LodgingConfiguration :
EntityTypeConfiguration<Lodging>
{
public LodgingConfiguration()
{
Property(l => l.Name).IsRequired().HasMaxLength(200);
}
}

然后再OnModelCreating中加进去,这个和modelBuilder.Entity<AnimalType>() 是同样的效果,modelBuilder.Entity<AnimalType>()会创建一个EntityTypeConfiguration。所以本质上他们是一样的代码。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new DestinationConfiguration());
modelBuilder.Configurations.Add(new LodgingConfiguration());
}
最好先支持数据迁移,不然模型改变会触发异常。
  public class VetContext:DbContext
    {
        public DbSet<Patient> Patients { get; set; }
        public DbSet<Visit> Visits { get; set; }

        public VetContext() : base("DefaultConnection")
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<VetContext, Configuration<VetContext>>());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<AnimalType>().ToTable("Animal");
            modelBuilder.Entity<AnimalType>().Property(p => p.TypeName).IsRequired();
        }
        
    }

    internal sealed class Configuration<TContext> : DbMigrationsConfiguration<TContext> where TContext : DbContext
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }
    }
View Code

 

相关文章:

  • 2022-12-23
  • 2021-06-17
  • 2022-02-26
  • 2021-11-17
  • 2022-12-23
  • 2021-06-02
  • 2021-07-24
  • 2021-11-24
猜你喜欢
  • 2021-10-28
  • 2022-12-23
  • 2021-05-25
  • 2022-02-05
  • 2021-10-29
  • 2022-12-23
  • 2021-12-13
相关资源
相似解决方案