在上一篇文章我们简单通过一个实例完成对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二(数据库对应映射)的更多相关文章

  1. 6.翻译系列:EF 6 Code-First中数据库初始化策略(EF 6 Code-First系列)

    原文链接:http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-firs ...

  2. 学习EF之CodeFirst一

    最近将花点时间学习EF相关知识,通过文章来进行一个完整的学习,Code First是由先有代码后生成数据库:将通过一实例来进行学习:我们简单分为三层,其中DataLibrary为EF上下文处理层,Mo ...

  3. 20.2.翻译系列:EF 6中基于代码的数据库迁移技术【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/code-based-migration-in-code-first.aspx EF 6 ...

  4. 20.翻译系列:Code-First中的数据库迁移技术【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/migration-in-code-first.aspx EF 6 Code-First ...

  5. 14.翻译系列:从已经存在的数据库中生成上下文类和实体类【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/code-first-from-existing-database.aspx EF 6 ...

  6. 5.翻译系列:EF 6中数据库的初始化(EF 6 Code-First 系列)

    原文地址:http://www.entityframeworktutorial.net/code-first/database-initialization-in-code-first.aspx EF ...

  7. 10.1.翻译系列:EF 6中的实体映射【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/configure-entity-mappings-using-fluent-api.a ...

  8. 10.2.翻译系列:使用Fluent API进行属性映射【EF 6 Code-First】

    原文链接:https://www.entityframeworktutorial.net/code-first/configure-property-mappings-using-fluent-api ...

  9. 21.翻译系列:Entity Framework 6 Power Tools【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/entity-framework-power-tools.aspx 大家好,这里就是EF ...

随机推荐

  1. JavaScript函数的防抖和节流

    防抖 触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间 思路: 每次触发事件时都取消之前的延时调用方法 function debounce(fn) { let tim ...

  2. 《深入浅出Nodejs》笔记——模块机制(1)

    前言 这是我读<深入浅出Nodejs>的笔记,真是希望我的机械键盘快点到啊,累死我了. CommonJS规范 主要分为模块引用.模块定义.模块标识三个部分. 模块引用 上下文提供requi ...

  3. 洛谷——P1068 分数线划定

    P1068 分数线划定 题目描述 世博会志愿者的选拔工作正在 A 市如火如荼的进行.为了选拔最合适的人才,A 市对 所有报名的选手进行了笔试,笔试分数达到面试分数线的选手方可进入面试.面试分数线根 据 ...

  4. Xamarin Android SDK无法更新的解决办法

    Xamarin Android SDK无法更新的解决办法   Xamarin Android SDK无法更新的解决办法,更新时候,提示警告信息:A folder failed to be moved. ...

  5. Gym - 101620I Intrinsic Interval

    题面在这里! 首先一个非常重要的性质是,两个好的区间的交依然是好的区间. 有了这个性质,我们只要找到包含某个区间的右端点最小的好区间,然后就是这个区间的答案拉. 至于找右端点最小的好区间就是一个扫描线 ...

  6. 【扫描线】Gym - 100781G - Goblin Garden Guards

    平面上有100000个哥布林和20000个圆,问你不在圆内的哥布林有多少个. 将每个圆从左到右切2r+1次,形成(2r+1)*2个端点,将上端点记作入点,下端点记作出点,再将这些点和那些哥布林一起排序 ...

  7. 记录SSD中的一些东西

    AnnotatedDatum是存放图片和BBox的类 // 估计是一张图片就对应于一个AnnotatedDatummessage AnnotatedDatum { enum AnnotationTyp ...

  8. for循环、for-in、forEach、for-of四大循环

    平时自己在写一些小栗子的时候,用到的基本上是for循环,因为在学专业课(C,C++,JAVA,...)的时候用的最多的就是for循环,不过for循环的效率也是比较高的. 但是for循环在写的时候,涉及 ...

  9. 93.数字三角形W(深搜)

    2189 数字三角形W  时间限制: 1 s  空间限制: 32000 KB  题目等级 : 黄金 Gold 题解 查看运行结果 题目描述 Description 数字三角形 要求走到最后mod 10 ...

  10. Nginx配置自签名的SSL证书(转载)

    要保证Web浏览器到服务器的安全连接,HTTPS几乎是唯一选择.HTTPS其实就是HTTP over SSL,也就是让HTTP连接建立在SSL安全连接之上. SSL使用证书来创建安全连接.有两种验证模 ...