How to apply Entity Framework code first approach to a project

陌路散爱 提交于 2021-01-28 19:54:47

问题


I use Visual Studio 2013 and need to use Entity Framework code first approach in a project. I used NuGet Manager to install EF v6.1 into my project. But I can't create an empty code first model or even a code first model from database although there are two other choices (DB first and Model first).

How I can add Entity Framework code first feature to my project?


回答1:


Here is a beginners tutorial for using entity framework code first: An Absolute Beginner's Tutorial for understanding Entity Framework's Code First Approach in ASP.NET MVC




回答2:


  1. Install EntityFramework In Nuget

  2. Add connectionString In Web.Config And YourConnection In The Name Of ConnectDB

  3. Add One Folder In The Name Of db

  4. In db Add Class In The Name Of Tbl_Student

    public class Tbl_Student
    {
        [Key]
        public int Id { get; set; }
    
        [Required(AllowEmptyStrings =false)]
        [StringLength(maximumLength:40)]
        public string Name { get; set; }
    
        [Required(AllowEmptyStrings = false)]
        [StringLength(maximumLength: 40)]
        public string Family { get; set; }
    }
    
  5. Out Of db Create One Class In The Name Of Context

  6. using System.Data.Entity;

  7. Edit Context To This

    public class DataContext:DbContext
    {
        public DataContext() : base("ConnectDB")
    {
    
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    }
    public virtual DbSet<Tbl_Student> Tbl_Students { get; set; }
    }
    
  8. To Package Maneger Console Write Enable-Migrations

  9. And Write Add-Migration mig1 since mig1 is desired

  10. After Write Update-DataBase



来源:https://stackoverflow.com/questions/23657655/how-to-apply-entity-framework-code-first-approach-to-a-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!