Entity Framework创建实体映射表字段信息

  1. 创建一个新表并建立和实体的映射:

首先是定义实体:

public class Person {

    [Key]

    public int SocialSecurityNumber { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

}

2. 创建实体的和数据库的中间层映射(映射存在于DbContext的子类):

public class BreakAwayContext : DbContext {

                   public DbSet<Person> Persons { get; set; }

}

3. 指定约束:

方式一:attribute方式,直接在字段上面添加约束;

public class Trip {

         [Key, DatabaseGeneratedOption.Identity]

        public Guid Identifier { get; set; }

}

方式二:在中间层以Fluent API方式指定(重写DbContext的OnModelCreating方法)

protected override void OnModelCreating(DbModelBuilder modelBuilder) {

    modelBuilder.Entity<Trip>().HasKey(p => p.Identifier);

    modelBuilder.Entity<Trip>().Property(p => p.Identifier).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

}

方式三:如果配置非常多,放在OnModelCreating中会显得很臃肿,那么就封装成EntityTypeConfiguration的类:

public class TripConfig : EntityTypeConfiguration<Trip> {

    public TripConfig() {

        HasKey(p => p.Identifier);

        Property(p => p.Identifier).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

    }

}

4.复杂类型

复杂类型仅仅是是为了实现应用层逻辑上面的一种封装,在数据库的表中依然是作为主表中的字段,而不是单独成表。

    1. 没有主键(如果有主键,那在生成的时候就会创建新表);
    2. 所有属性的字段必须是.net原生类型(Primitive Type);
    3. 不能是List,这能是单一实例。

public class Person {

    public Person() {

        this.Address = new Address();

    }

   …

    public Address Address { get; set; }

}

 

public class Address {

    public string StreetAddress { get; set; }

    public string City { get; set; }

    public string State { get; set; }

    public string ZipCode { get; set; }

}

最终,形成的表结构如下所示:

                       

 

posted on 2013-03-26 21:29  下士闻道  阅读(435)  评论(0编辑  收藏  举报

导航