要更改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(10),MaxLength(30)]
public string Name { get; set; }
[StringLength(30)]
public string Country { get; set; }

Fluent API:没有设置最小长度这个方法。

modelBuilder.Entity<Destination>().Property(p => p.Name).HasMaxLength(30);
modelBuilder.Entity<Destination>().Property(p => p.Country).HasMaxLength(30);

非空

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

如果我的文章对你有帮助,就点一下推荐吧.(*^__^*)

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. jQuery 的 json 格式的处理问题

    在实际的使用中时常会发生一些ajax验证的诡异事件,如我在一个文件中使用json传送数据,结果出现了当数据发送到服务器端时(后端主要呈现的是对json数据对象的数据库查询操作),结果显示的是数据已经插 ...

  2. Java实现mysql数据库备份

    Runtime是一个与JVM运行时环境有关的类,这个类是Singleton的. Runtime.getRuntime()可以取得当前JVM的运行时环境,这也是在Java中唯一一个得到运行时环境的方法. ...

  3. EXTJS 4.2 资料 控件之 xtype: "fieldcontainer",追加html

    { xtype: "fieldcontainer", layout: "hbox", items: [ { fieldLabel: '素材目录', name: ...

  4. 一种高斯模糊渐变动画的实现-b

    关于高斯模糊的方式有很多种,但是如果需要模糊渐变,那么对这种高斯模糊算法的性能要求是比较高的,今天这里重点不讨论算法,只是提供一个动画实现的思路.动画效果如下: 高斯模糊渐变动画 //高斯模糊 -(U ...

  5. vbe6ext.olb不能被加载 宏内存溢出

    今天想玩一下PowerPoint的宏,却发现玩不起来!!! 另外,每次打开ppt时都会提示vbe6ext.olb不能加载. 网上说重新下载个vbe6ext.olb然后复制到相应的路径.我也试着下载,然 ...

  6. DataGridView 列自适应宽度 设置

    代码: Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; 或者设置DataGridView的AutoSizeColu ...

  7. The 7th Zhejiang Provincial Collegiate Programming Contest->Problem B:B - Somali Pirates

    http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3323 题意:去掉字符串里面的数字然后按输入顺序输出 #include< ...

  8. Educational Codeforces Round 5 A

    Problem A:http://codeforces.com/contest/616/problem/A A. Comparing Two Long Integers 果然还是我太天真了(长整数比较 ...

  9. 一个HexToInt的C/C++函数

    int  BetterVenca25(char* hex){   int res=0;   for(;*hex;hex++)   {  int d=toupper(*hex);      if(d & ...

  10. POJ 1061 青蛙的约会(扩展欧几里德)

    点我看题目 题意 : 中文题不详述. 思路 : 设经过s步后两青蛙相遇,则必满足(x+m*s)-(y+n*s) = K*L(k = 0,1,2....) 变形得:(n-m)*s+K*L = x-y ; ...