CodeFirst试水

来源:互联网 发布:网络教育本科毕业证 编辑:程序博客网 时间:2024/05/17 21:38

之前试用Entity Framework做DATABASE First,使用起来确实是方便,奈何数据库也是边做边改,简直就是灾难。

看来还是避不开CodeFirst,只好硬着头皮试。

不试还好,一整一天,怎么调试都是【配置系统未能初始化】

搞到最后,竟然只是配置文件中的节点顺序不对,无语了!

记录一下:

一、配置节点顺序一点不能乱

<configuration>
    <configSections>//第一节点
    <connectionStrings>//第二节点

<?xml version="1.0" encoding="utf-8"?><configuration>  <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" />    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->  </configSections>  <connectionStrings>    <add name="ModelFirstKey" connectionString="server=.;uid=sa;pwd=chenxq@5210;database=CodeFirstDemoDB;" providerName="System.Data.SqlClient" />  </connectionStrings>  <startup>    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />  </startup>  <entityFramework>    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">      <parameters>        <parameter value="mssqllocaldb" />      </parameters>    </defaultConnectionFactory>    <providers>      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />    </providers>  </entityFramework></configuration>
二、建立模型和上下文
    public class UserInfo    {        public UserInfo()        {            OrderInfo = new HashSet<OrderInfo>();        }        [Key]        public int UserID { get; set; }//主键        public string UserName { get; set; }        public virtual ICollection<OrderInfo> OrderInfo { get; set; }//导航属性    }    public class OrderInfo    {        [Key]        public int ID { get; set; }        public string OrderContent { get; set; }        public virtual UserInfo UserInfo { get; set; }    }    public class CodeFirstDbContext:DbContext    {        public CodeFirstDbContext()              : base("name=ModelFirstKey")        {        }        protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();//去掉生成表名复数s        }        public DbSet<UserInfo> UserInfo { get; set; }        public DbSet<OrderInfo> OrderInfo { get; set; }    }
三、调用

        private void button1_Click(object sender, EventArgs e)        {            using (CodeFirstDbContext dbContext = new CodeFirstDbContext())            {                dbContext.Database.CreateIfNotExists();                UserInfo userInfo = new UserInfo();                userInfo.UserName = "xiaoyang";                dbContext.UserInfo.Add(userInfo);                dbContext.SaveChanges();            }        }



0 0
原创粉丝点击