要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就是Fluent API,通过新增相应的配置类来覆盖默认配置。现在我们用这两个来对比了解EF中的约定配置。

主键:KEY

Data Annotations:通过Key关键字来标识一个主键

[Key]
public int DestinationId { get; set; }

Fluent API:

public class BreakAwayContext : DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Fluent API
modelBuilder.Entity<Destination>().HasKey(d => d.DestinationId);
base.OnModelCreating(modelBuilder);
}
}

外键

Data Annotations:

public int DestinationId { get; set; }
[ForeignKey("DestinationId")]
public Destination Destination { get; set; }

注意,指定列名存在,如上面的DestinationId,则类中必须存在名称为DestinationId的属性。

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来标识,还可以设置是否可允许空字符串,显示错误消息等。

[Required]
public string Country { get; set; }
[Required(ErrorMessage="请输入描述")]
public string Description { get; set; }

Fluent API:

modelBuilder.Entity<Destination>().Property(p => p.Country).IsRequired();

数据类型

Data Annotations:TypeName

//将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

[Table("MyLodging")]
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public decimal Price { get; set; }
public bool IsResort { get; set; }
public Destination Destination { get; set; }
}

Fluent API:

modelBuilder.Entity<Lodging>().ToTable("MyLodging");

列名

Data Annotations:Column

[Column("MyName")]
public string Name { get; set; }

Fluent API:

modelBuilder.Entity<Lodging>().Property(p => p.Name).HasColumnName("MyName");

自增长

如果主键是int类型,EF为默认设置为增长。但如果是GUID类型,则要显示的设置自增长。

Data Annotations:DatabaseGenerated

public class Person
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid SocialId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

看看创建数据的脚本,会加一句

ALTER TABLE [dbo].[People] ADD  DEFAULT (newid()) FOR [SocialId]

Fluent API:

modelBuilder.Entity<Person>().Property(p => p.SocialId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

忽略列映射

类中有些属性,特别是一些通过计算或合并列得出的结果,我们并不需要其记录到数据库中,就可以通过配置不让它生成在数据库中。

Data Annotations:NotMapped

[NotMapped]
public string Name
{
get
{
return FirstName + " " + LastName;
}
}

Fluent API:NotMapped

modelBuilder.Entity<Person>().Ignore(p => p.Name);

忽略表映射

对于不需要映射到数据库中的表,我们也可以取消其映射。

Data Annotations:

[NotMapped]
public class Person
{
[Key]
public Guid SocialId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

Fluent API:

modelBuilder.Ignore<Person>();

时间戳

时间戳只对数据类型为byte[]的属性有效,并且一个类中只能有一个设置为时间戳的属性。

Data Annotations:Timestamp

[Timestamp]
public Byte[] TimeStamp { get; set; }

Fluent API:

modelBuilder.Entity<Lodging>().Property(p => p.TimeStamp).IsRowVersion();

复杂类型

Data Annotations:ComplexType

[ComplexType]
public class Address
{
public string Country { get; set; }
public string City { get; set; }
}

Fluent API:

modelBuilder.ComplexType<Address>();

关于什么是复杂类型,可以参见:http://www.cnblogs.com/Gyoung/archive/2013/01/17/2864747.html

--------------------------------------------------------------------------------
From: http://www.cnblogs.com/Gyoung/archive/2013/01/17/2864150.html

[转载]EF Code First 学习笔记:约定配置的更多相关文章

  1. EF Code First 学习笔记:约定配置 Data Annotations+Fluent API

    要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就 ...

  2. EF Code First 学习笔记:约定配置

    要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就 ...

  3. 【转】EF Code First 学习笔记:约定配置

    要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就 ...

  4. EF Code First 学习笔记:约定配置(转)

      要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一 ...

  5. EF Code First学习笔记

    EF Code First学习笔记 初识Code First EF Code First 学习笔记:约定配置 Entity Framework 复杂类型 Entity Framework 数据生成选项 ...

  6. EF Code First教程-02 约定配置

    示例: public class Phone { [Key] //主键 public int Id { get; set; } [Required] //不能为空 [MinLength(),MaxLe ...

  7. EF Code First学习笔记:数据库创建

    控制数据库的位置 默认情况下,数据库是创建在localhost\SQLEXPRESS服务器上,并且默认的数据库名为命名空间+context类名,例如我们前面的BreakAway.BreakAwayCo ...

  8. EF Code First 学习笔记:表映射

    多个实体映射到一张表 Code First允许将多个实体映射到同一张表上,实体必须遵循如下规则: 实体必须是一对一关系 实体必须共享一个公共键 观察下面两个实体: public class Perso ...

  9. EF Code First 学习笔记:表映射 多个Entity到一张表和一个Entity到多张表

      多个实体映射到一张表 Code First允许将多个实体映射到同一张表上,实体必须遵循如下规则: 实体必须是一对一关系 实体必须共享一个公共键 观察下面两个实体: public class Per ...

随机推荐

  1. VirtualBox是什么

    VirtualBox 是一款 x86 虚拟机软件.原由德国innotek公司开发,2008年Sun收购了Innotek,而Sun于2010年被Oracle收购,2010年1月21日改 名成 Oracl ...

  2. XSS测试语句大全

    '><script>alert(document.cookie)</script> ='><script>alert(document.cookie)& ...

  3. 《深入剖析Tomcat》读书笔记(二)

    三.容器Container Container 是容器的父接口,所有子容器都必须实现这个接口.Container 容器的设计用的是典型的责任链的设计模式,它有四个子容器组件构成,分别是:Engine. ...

  4. wpf常见枚举收集

    Icons made by from www.flaticon.com

  5. string,stringbuilder,stringbuffer

    String可以储存和操作字符串,即包含多个字符的字符数据.这个String类提供了存储数值不可改变的字符串. StringBuilder是线程不安全的,运行效率高,如果一个字符串变量是在方法里面定义 ...

  6. 整理一些有意思的php笔试题

    慢慢补充 1.下面这段代码的输出是什么: $a = in_array('01', array('1'))==var_dump('01'==1); echo $a; 说明:in_array('01', ...

  7. 《安全参考》HACKCTO-201311-11

    小编的话 “晴空一鹤排云去,便引诗情到碧宵” 11月是一个让人思绪飞扬.感慨万千的时节. 就在这时,在我们小伙伴的并肩奋战下,第十一期<安全参考>又跟大家见面了. 你还在为女朋友在购物狂欢 ...

  8. Enum枚举类型的使用笔记

    好处: 1.可以直接使用switch 2.可以实现toString()方法 笔记: 1.枚举类头部定义的成员变量,可以看做是枚举类的一个实例 public enum Color { RED(" ...

  9. 重回程序员之路。重写博客。我的ecshop小京东二开问题汇总与解决方案。

    问题1:混合支付(余额支付+在线支付)不跟更新订单状态问题. 解决方案:http://bbs.ecshop.com/viewthread.php?tid=156761&highlight= i ...

  10. 11)Java abstract class 和 interface

    abstract class 和 interface 的区别        含有abstract修饰符的class即为抽象类,abstract 类不能创建实例对象.含有abstract方法的类必须定义 ...