需要引入的框架:
实体类:
[Table("Users")]
internal class User
{[Key]public int Id { get; set; }[Required][StringLength(100)][Index(IsUnique = true)]public string Username { get; set; }[Required][StringLength(100)]public string Password { get; set; }public bool IsAdmin { get; set; }
}
连接类:
internal class MyDbContext : DbContext
{private static string IP = "localhost";private static string DB = "BookShop";private static string User_Id = "sa";private static string PASSWORD = "root";public DbSet<User> Users { get; set; }public MyDbContext() : base($"Server='{IP}';Database='{DB}';User Id='{User_Id}';Password='{PASSWORD}';") { }
}
演示的案例:
static void Main(string[] args)
{MyDbContext db = new MyDbContext();IList<User> users = db.User.ToList();// 或者using (MyDbContext db2 = new MyDbContext()) { }
}