当前位置: 移动技术网 > IT编程>开发语言>.net > CODE FIRST之空数据模型

CODE FIRST之空数据模型

2019年02月25日  | 移动技术网IT编程  | 我要评论

说出你的故事sjm,windows ce软件,三水吉右卫门

1、首先添加空code firtst模型

 

2、新建两个实体类,关系一对多

    public class userinfo
    {
        public userinfo()
        {
            orderinfo = new hashset<orderinfo>();
        }

        [key]
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }

        public virtual icollection<orderinfo> orderinfo { get; set; }
    }
    public class orderinfo
    {
        public int id { get; set; }
        public string content { get; set; }

        public virtual userinfo userinfo { get; set; }
    }

  

3、修改模型文件,启用实体类

public class codefirst : dbcontext
    {
        //您的上下文已配置为从您的应用程序的配置文件(app.config 或 web.config)
        //使用“codefirst”连接字符串。默认情况下,此连接字符串针对您的 localdb 实例上的
        //“codefirstdemo.codefirst”数据库。
        // 
        //如果您想要针对其他数据库和/或数据库提供程序,请在应用程序配置文件中修改“codefirst”
        //连接字符串。
        public codefirst()
            : base("name=codefirst")
        {
        }

        //为您要在模型中包含的每种实体类型都添加 dbset。有关配置和使用 code first  模型
        //的详细信息,请参阅 http://go.microsoft.com/fwlink/?linkid=390109。

        public virtual dbset<userinfo> userinfo { get; set; }
        public virtual dbset<orderinfo> orderinfo { get; set; }
    }

 

4、修改app.config文件连接属性,此处database不存在

<connectionstrings>
    <add name="codefirst" connectionstring="data source=****;user id=sa;password=****;database=codetest;multipleactiveresultsets=true;app=entityframework" providername="system.data.sqlclient" />
</connectionstrings>

 

5、在代码中创建数据库并插入数据

codefirst dbcontext = new codefirst( );
dbcontext.database.createifnotexists();

userinfo userinfo = new userinfo();
userinfo.age = 10;
userinfo.id = 1;
userinfo.name = "张三";
dbcontext.userinfo.add(userinfo);
dbcontext.savechanges();

console.writeline("ok");

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网