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; } }
public class EfDbContext : DbContext { public EfDbContext() { } public DbSet<Blog> Blogs { get; set; } }
注:上下文派生类中定义DbSet有以下三种方式:数据库
//用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>();} } }
static void Main(string[] args) { using (var efDbContext = new EfDbContext()) { efDbContext.Blogs.Add(new Blog() { Name = "张三", Url = "http://www.baidu.com" }); efDbContext.SaveChanges(); } }
注:若是未找到或没法访问服务器的错误,则说明你本地vs未安装LocalDB数据库,这时你能够安装LocalDB数据库,或者在App.config中将链接字符串修改成SQL Server 数据库的地址。