首页 > 代码库 > Entity Framework Code First to a New Database
Entity Framework Code First to a New Database
1. Create the Application
To keep things simple we’re going to build a basic console application that uses Code First to perform data access.
- Open Visual Studio
- File -> New -> Project…
- Select Windows from the left menu and Console Application
- Enter CodeFirstNewDatabaseSample as the name
- Select OK
2. Create the Model
public class Department { [Key] public int DepartmentID { get; set; } public int CourseID { get; set; } [ForeignKey("CourseID")] public Course Course { get; set; } public string Name { get; set; } }
3. Create a Context
- Project –> Manage NuGet Packages… Note: If you don’t have the Manage NuGet Packages… option you should install the latest version of NuGet
- Select the Online tab
- Select the EntityFramework package
- Click Install
public class QxunDbContext : DbContext { public QxunDbContext() : base("server=localhost;uid=sa;pwd=6665508a;database=Qxun;") { } public DbSet<Department> Departments { get; set; } }
4. Reading & Writing Data
using (var db = new BloggingContext()) { // Create and save a new Blog Console.Write("Enter a name for a new Blog: "); var name = Console.ReadLine(); var blog = new Blog { Name = name }; db.Blogs.Add(blog); db.SaveChanges(); // Display all Blogs from the database var query = from b in db.Blogs orderby b.Name select b; Console.WriteLine("All blogs in the database:"); foreach (var item in query) { Console.WriteLine(item.Name); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
Entity Framework Code First to a New Database
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。