EF设计模式之code first

为了支持以设计为中心的开发流程,EF推出了以代码为中心的模式code first。我们称之为代码优先开发,代码优先的开发支持更加优美的开发流程,允许在不使用设计器或者定义一个XML映射文件的情况下进行开发。对数据库的操作不需要通过sql语句完成。

在MVC中使用code first

1、添加引用EntityFramework.dll和针对于sql server数据库的EntityFarmework.SqlServer.dll文件

2、在Web.config文件中添加数据库连接字符串

3、数据访问层指向配置文件

namespace DAL
{
    public class MyContent:DbContext
    {
        public MyContent() : base("name=XXX")
        {

        }
        public DbSet<StudentInfo> stu { get; set; }
    }
}

4、实现数据操作

public class StudentDal : IDataServer<StudentInfo>
    {
        MyContent myc = new MyContent();
        public int Create(StudentInfo t)
        {
            myc.stu.Add(t);
            return myc.SaveChanges();
        }

        public int Delete(int id)
        {
            var stu = myc.stu.Where(m=>m.Id==id).FirstOrDefault();
            myc.Entry(stu).State = System.Data.Entity.EntityState.Deleted;
            return myc.SaveChanges();
        }

        public List<StudentInfo> GetAll()
        {
            return myc.stu.ToList();
        }

        public StudentInfo GetAllById(int id)
        {
            return myc.stu.Where(m => m.Id == id).FirstOrDefault();
        }

        public int Update(StudentInfo t)
        {
            myc.Entry(t).State = System.Data.Entity.EntityState.Modified;
            return myc.SaveChanges();
        }
    }
原文地址:https://www.cnblogs.com/dujian123/p/10580565.html