一.SQLServer数据库创建表Company,包含ID,CName,IsEnabled三列
二.(1)VS新建一个DXApplication工程,名为CompanyManageSystem
(2)在工程下,右键点击“引用” -> "管理NuGet程序包" -> "浏览" -> 找到"EntityFramework" -> 点击“安装”
(3)新建一个类PSContext.cs
namespace CompanyManageSystem
{
class PSContext : DbContext
{
public PSContext() : base("name=PSContext"){}
public virtual DbSet<Company> Companys { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
}
(4)新建一个类Company.cs
namespace CompanyManageSystem.Model
{
[Table("Company")]
public class Company
{
public Guid ID { get; set; }
public String CName { get; set; }
public bool IsEnabled { get; set; }
}
}
(5)在App.config添加数据库的代码
<?xml version="1.0" encoding="utf-8"?> <configuration> <connectionStrings> <add name="PSContext" connectionString="data source=X450V-PC;initial catalog=date;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>
(6)添加窗体Frm_ShowInfo.cs (注意:FiledName里面的名字要和数据库的列名相同,(Name)里面的名字尽量不取Name)
添加控件如图所示:
namespace CompanyManageSystem { public partial class Frm_ShowInfo : Form { PSContext _db = new PSContext(); public Frm_ShowInfo() { InitializeComponent(); } private void Frm_ShowInfo_Load(object sender, EventArgs e) { CompanyGrid.DataSource = _db.Companys.AsNoTracking().ToList(); } } }
(7)在Program.cs启动Frm_ShowInfo.cs窗口
namespace CompanyManageSystem { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); BonusSkins.Register(); SkinManager.EnableFormSkins(); UserLookAndFeel.Default.SetSkinStyle("DevExpress Style"); Application.Run(new Frm_ShowInfo()); } } }
实体加载MySQL数据库
1.需要在“管理NuGet程序包”里面安装装“MySql.Data”和“MySql.Data.Entity” 2.配置App.config文件 <connectionStrings> <add name="PSContext" connectionString="Data Source=192.168.3.16;port=3306;Initial Catalog=tsyw;user id=root;password=123456;Charset=utf8" providerName="MySql.Data.MySqlClient" /> </connectionStrings>
3.其余部分和SQLServer一样
延伸知识(本地数据库或其它服务器)
<connectionStrings> <!--<add name="ConnectionStrings" connectionString="Data Source=localhost;Initial Catalog=TSYW;User ID=sa;Password=2277092;Persist Security Info=True;" providerName="System.Data.SqlClient" />--> <!--<add name="ConnectionStrings" connectionString="data source=X450V-PC;initial catalog=TSYW;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />--> <add name="PSContext" connectionString="Data Source=127.0.0.1;port=3306;Initial Catalog=tsyw;user id=root;password=123456;Charset=utf8" providerName="MySql.Data.MySqlClient" /> </connectionStrings>