学习EF之CodeFirst二(数据库对应映射)
在上一篇文章我们简单通过一个实例完成对CodeFirst的理解,我们通过实体生成数据库里的表和字段,虽然有一些默认的配置生成规定,但其实我们可以能过对实体进一步控制从而对生成的表字段进行更加符合我们要求的控制;比如主键、非空、范围大小不、字段名称等等;主要有两种方式(1)Data Annotations(2)Fluent API
一:Data Annotations
此方法是利用在实体的那个属性里增加特性来进行操作控制;这些特性是在using System.ComponentModel.DataAnnotations下,要引用DLL
using System.ComponentModel.DataAnnotations;
namespace ModelLib
{
public class Car
{
[Key]
public int ID { get; set; } [Required(ErrorMessage="不能为空")]
public string CarNum { get; set; } [StringLength(,ErrorMessage="最大长度不能超过10个字符")]
public string Colour { get; set; } [Range(,,ErrorMessage="UserYear取证范围在1-10之间")]
public int UserYear { get; set; } [RegularExpression(@"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$")]
public string Email { get; set; }
}
}
假如我们代码没有按照上面规定来便会报出异常:
上面只是列出一部分的特性,其它特性可以查MSDN:http://msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations.aspx



二:Fluent API(推荐使用,因为前一种范围有限)
1:我们可以在EF上下文里重写OnModelCreating然后对要设置的属性进行操作,但是这样一个实体类如果有3个属性需要配置,10个实体类就需要配置30个,那么就得在OnModelCreating方法里写30行,很麻烦且不易维护,所以一般不这么编写;
using System.Data.Entity;
using ModelLib;
namespace DataLibrary
{
public class MyDbContext : DbContext
{
public MyDbContext()
: base("name=MyTestDb")
{
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Home>().HasKey(d => d.ID);
modelBuilder.Entity<Home>().Property(d => d.Address).IsRequired();
modelBuilder.Entity<Person>().Property(p => p.PassWord).HasMaxLength();
} public DbSet<Person> Person { get; set; } public DbSet<Home> Home { get; set; } public DbSet<Car> Car { get; set; }
}
}
2:注意返回值可以看出modelBuilder的Entity<>泛型方法的返回值是EntityTypeConfiguration<>泛型类。我们可以定义一个继承自EntityTypeConfiguration<>泛型类的类来定义domain中每个类的数据库配置。
ok,我们在DataAccess类库下新建一个继承自EntityTypeConfiguration<>泛型类的DestinationMap类,在构造函数里写上配置:
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using ModelLib;
namespace DataLibrary
{
public class HomeMap:EntityTypeConfiguration<Home>
{
public HomeMap()
{
Property(d => d.Address).IsRequired();
}
}
}
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using ModelLib; namespace DataLibrary
{
public class PersonMap:EntityTypeConfiguration<Person>
{
public PersonMap()
{
Property(d => d.Age).IsRequired();
}
}
}
然后修改EF上下文:
using System.Data.Entity;
using ModelLib;
namespace DataLibrary
{
public class MyDbContext : DbContext
{
public MyDbContext()
: base("name=MyTestDb")
{
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new HomeMap());
modelBuilder.Configurations.Add(new PersonMap());
} public DbSet<Person> Person { get; set; } public DbSet<Home> Home { get; set; } public DbSet<Car> Car { get; set; }
}
}
下面是一些常用的设置:
//【主键】
//Data Annotations:
[Key]
public int DestinationId { get; set; } //Fluent API:
public class BreakAwayContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Destination>().HasKey(d => d.DestinationId);
}
} //【外键】
//Data Annotations:
public int DestinationId { get; set; }
[ForeignKey("DestinationId")]
public Destination Destination { get; set; } //Fluent API:
modelBuilder.Entity<Lodging>().HasRequired(p => p.Destination).WithMany(p=>p.Lodgings).HasForeignKey(p => p.DestinationId); //【长度】
//Data Annotations:通过StringLength(长度),MinLength(最小长度),MaxLength(最大长度)来设置数据库中字段的长度
[MinLength(),MaxLength()]
public string Name { get; set; }
[StringLength()]
public string Country { get; set; } //Fluent API:没有设置最小长度这个方法
modelBuilder.Entity<Destination>().Property(p => p.Name).HasMaxLength();
modelBuilder.Entity<Destination>().Property(p => p.Country).HasMaxLength(); //【非空】
//Data Annotations:
[Required(ErrorMessage="请输入描述")]
public string Description { get; set; } //Fluent API:
modelBuilder.Entity<Destination>().Property(p => p.Country).IsRequired(); //【数据类型】
Data Annotations:
将string映射成ntext,默认为nvarchar(max)
[Column(TypeName = "ntext")]
public string Owner { get; set; } //Fluent API:
modelBuilder.Entity<Lodging>().Property(p => p.Owner).HasColumnType("ntext"); //【表名】
//Data Annotations:
[Table("MyLodging")]
public class Lodging
{
} //Fluent API
modelBuilder.Entity<Lodging>().ToTable("MyLodging"); //【列名】
//Data Annotations:
[Column("MyName")]
public string Name { get; set; } //Fluent API:
modelBuilder.Entity<Lodging>().Property(p => p.Name).HasColumnName("MyName"); //【自增长】
//Data Annotations
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] Guid类型的主键、自增长
public Guid SocialId { get; set; } //Fluent API:
modelBuilder.Entity<Person>().Property(p => p.SocialId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); //【忽略列映射】
//Data Annotations:
[NotMapped]
public string Name
{
get
{
return FirstName + " " + LastName;
}
} //Fluent API:
modelBuilder.Entity<Person>().Ignore(p => p.Name); //【忽略表映射】
//Data Annotations:
[NotMapped]
public class Person
{ } //Fluent API:
modelBuilder.Ignore<Person>(); //【时间戳】
//Data Annotations:Timestamp
[Timestamp]
public Byte[] TimeStamp { get; set; } 只能是byte类型 //Fluent API:
modelBuilder.Entity<Lodging>().Property(p => p.TimeStamp).IsRowVersion(); //【复杂类型】
//Data Annotations:
[ComplexType]
public class Address
{
public string Country { get; set; }
public string City { get; set; }
} //Fluent API:
modelBuilder.ComplexType<Address>();
学习EF之CodeFirst二(数据库对应映射)的更多相关文章
- 6.翻译系列:EF 6 Code-First中数据库初始化策略(EF 6 Code-First系列)
原文链接:http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-firs ...
- 学习EF之CodeFirst一
最近将花点时间学习EF相关知识,通过文章来进行一个完整的学习,Code First是由先有代码后生成数据库:将通过一实例来进行学习:我们简单分为三层,其中DataLibrary为EF上下文处理层,Mo ...
- 20.2.翻译系列:EF 6中基于代码的数据库迁移技术【EF 6 Code-First系列】
原文链接:https://www.entityframeworktutorial.net/code-first/code-based-migration-in-code-first.aspx EF 6 ...
- 20.翻译系列:Code-First中的数据库迁移技术【EF 6 Code-First系列】
原文链接:https://www.entityframeworktutorial.net/code-first/migration-in-code-first.aspx EF 6 Code-First ...
- 14.翻译系列:从已经存在的数据库中生成上下文类和实体类【EF 6 Code-First系列】
原文链接:https://www.entityframeworktutorial.net/code-first/code-first-from-existing-database.aspx EF 6 ...
- 5.翻译系列:EF 6中数据库的初始化(EF 6 Code-First 系列)
原文地址:http://www.entityframeworktutorial.net/code-first/database-initialization-in-code-first.aspx EF ...
- 10.1.翻译系列:EF 6中的实体映射【EF 6 Code-First系列】
原文链接:https://www.entityframeworktutorial.net/code-first/configure-entity-mappings-using-fluent-api.a ...
- 10.2.翻译系列:使用Fluent API进行属性映射【EF 6 Code-First】
原文链接:https://www.entityframeworktutorial.net/code-first/configure-property-mappings-using-fluent-api ...
- 21.翻译系列:Entity Framework 6 Power Tools【EF 6 Code-First系列】
原文链接:https://www.entityframeworktutorial.net/code-first/entity-framework-power-tools.aspx 大家好,这里就是EF ...
随机推荐
- Mac OS X 更新JAMF域控配置
在终端执行以下命令即可更新jamf域控配置属性 sudo jamf mcx # 应用被管理的配置信息 sudo jamf policy -trigger # 检查触发器策略 sudo jamf rec ...
- 大数据技术之_16_Scala学习_05_面向对象编程-中级
第七章 面向对象编程-中级7.1 包7.1.1 Java 中的包7.1.2 Scala 中的包7.1.3 Scala 包的特点概述7.1.4 Scala 包的命名7.1.5 Scala 会自动引入的常 ...
- SpringBoot整合SpringSecurity简单实现登入登出从零搭建
技术栈 : SpringBoot + SpringSecurity + jpa + freemark ,完整项目地址 : https://github.com/EalenXie/spring-secu ...
- [P4064][JXOI2017]加法(贪心+树状数组+堆)
题目描述 可怜有一个长度为 n 的正整数序列 A,但是她觉得 A 中的数字太小了,这让她很不开心. 于是她选择了 m 个区间 [li, ri] 和两个正整数 a, k.她打算从这 m 个区间里选出恰好 ...
- BZOJ 4059 [Cerc2012]Non-boring sequences(启发式分治)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=4059 [题目大意] 一个序列被称为是不无聊的,仅当它的每个连续子序列存在一个独一无二的 ...
- 【推导】【构造】XVII Open Cup named after E.V. Pankratiev Stage 14, Grand Prix of Tatarstan, Sunday, April 2, 2017 Problem E. Space Tourists
给你n,K,问你要选出最少几个长度为2的K进制数,才能让所有的n位K进制数删除n-2个元素后,所剩余的长度为2的子序列至少有一个是你所选定的. 如果n>K,那么根据抽屉原理,对于所有n位K进制数 ...
- 【动态规划】【记忆化搜索】hdu5965 扫雷
f(i,j,k)表示第i行,放的雷的状态为j{0表示不放,1表示往上放,2表示往下放,3表示上下都放},剩余还有k(0<=k<=2)个要放的方案数. 先给出我这个sb写的错误代码,死都没调 ...
- 【数论】nefu119 组合素数
算组合数中的素因子p的个数,基本同这题 http://www.cnblogs.com/autsky-jadek/p/6592194.html #include<cstdio> using ...
- Problem D: 指针:调用自定义排序函数sort,对输入的n个数进行从小到大输出。
#include<stdio.h> int sort(int *p,int n) { int i,j,temp; ;i<n-;i++) for(j=i;j<n;j++) if( ...
- es进行聚合操作时提示Fielddata is disabled on text fields by default
在进行派粗前,先执行以下操作 { "properties": { "updatedate": { "type": "text&qu ...