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 數據庫的地址。