3102—EF随笔—Code First

1—首先在程序中建立表

      在Model文件夹中建立表PersonModel。

      引入2个空间      

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

     实体类定义

[Table("T_user")]
 public class Person
    {
        [Key]
        public int Fid { get; set; }

        [StringLength(100)]
        [Required(ErrorMessage="请输入姓名")]
        public string Fname { get; set; }

        [StringLength(20)]
        public string Fsex { get; set; }
                
        public int Fage { get; set; }
        
        [StringLength(200)]
        public string Faddress { get; set; }

        [StringLength(100)]
        public string Fphone { get; set; }
    }

2—写入app.config连接字符串     

<configuration>
    <!--  使用EF框架     -->
    <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>

  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient"     type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

    <!--   数据库连接参数    -->
      <connectionStrings>
          <add name="myDbConn" connectionString="Data Source=vpc05;Initial Catalog=ef1-2;Persist Security Info=True;user id=sa;password=****" providerName="System.Data.SqlClient"    />    
 
      </connectionStrings>
</configuration>

3—建立DAL数据库存取类  

/*
     * 数据库上下文
     * 继承自DbContext
     */
    public    class myDbDAL:DbContext
    {
        static myDbDAL() 
        {
            Database.SetInitializer<myDbDAL>(new DropCreateDatabaseIfModelChanges<DbContext>()  );      
        }
        public myDbDAL()
            : base("name=myDbConn") 
        {
            //name取值自App.config中的add name值
        }
        
        public DbSet<Person> Persons { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Person>().ToTable("T_user");            
            base.OnModelCreating(modelBuilder);
        }
    }

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值