Entity Framework first experience

Zero, first experience

  1. New console program, entitled: MyFirstEF
  2. Search NuGet in the Entity Framework , as shown below:

  1. Create a Blog category:
public class Blog
{
  public int Id { get; set; }
  public string Name { get; set; }
  public string Url { get; set; }
  public DateTime? CreatedTime { get; set; }
  public double Double { get; set; }
  public float Float { get; set; }
}
复制代码
  1. Create a class that inherits from EF context, and this context is an intermediate bridge database interaction, we can call the session, and open a DbSet for each model:
public class EfDbContext : DbContext
{
  public EfDbContext()
  {
  }

  public DbSet<Blog> Blogs { get; set; }
}
复制代码

Note: in the context of a derived class is defined DbSet following three ways:

//用DbSet属性
public class EfDbContext : DbContext
{
  public EfDbContext()
  {
  }

  public DbSet<Blog> Blogs { get; set; }
}

//用IDbSet属性
public class EfDbContext : DbContext
{
  public IDbSet<Blog> Blogs { get; set; }
}

//只读属性
public class EfDbContext : DbContext
{

  public DbSet<Blog> Blogs
  {
    get {return Set<Blog>();}
  }
}
复制代码
  1. Add the following code in the main functions:
static void Main(string[] args)
{
  using (var efDbContext = new EfDbContext())
  {
      efDbContext.Blogs.Add(new Blog()
      {
          Name = "张三",
          Url = "http://www.baidu.com"
      });
      efDbContext.SaveChanges();
  }
}
复制代码
  1. Run console programs, if any error does not appear, you will see the newly created VS corresponding local database Blogs tables and a new data.

Note: If you do not find or can not access the wrong server, then you have not LocalDB vs local database installation, then you can install LocalDB database connection string or modified to address SQL Server database in the App.config.

Reproduced in: https: //juejin.im/post/5d01b808e51d45772a49ad2f

Guess you like

Origin blog.csdn.net/weixin_34387284/article/details/93169917
Recommended