usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Data.Entity;namespacecodefirstnewdatabasesample{ Public classBlog { Public intBlogId {Get;Set; } Public stringName {Get;Set; } Public VirtualList<post> Posts {Get;Set; } } Public classPost { Public intPostID {Get;Set; } Public stringTitle {Get;Set; } Public stringContent {Get;Set; } Public intBlogId {Get;Set; } Public VirtualBlog Blog {Get;Set; } } Public classBloggingcontext:dbcontext { PublicBloggingcontext ():Base("Name=blogcontext") { } PublicDbset<blog> Blogs {Get;Set; } PublicDbset<post> Posts {Get;Set; } } classProgram {Static voidMain (string[] args) { using(vardb =NewBloggingcontext ()) { //Create and save a new BlogConsole.Write ("Enter a name for a new Blog:"); varName =Console.ReadLine (); varBlog =NewBlog {Name =name}; Db. Blogs.add (blog); Db. SaveChanges (); //Display all Blogs from the database varquery = fromBinchdb. Blogs byB.nameSelectb; Console.WriteLine ("All blogs in the database:"); foreach(varIteminchquery) {Console.WriteLine (item. Name); } Console.WriteLine ("Press any key to exit ..."); Console.readkey (); } } }}
Add a service-based database
Public bloggingcontext () Base ("name=blogcontext") {} //strings Attached
Or
Public bloggingcontext () Base ("blogcontext") {} // strings attached
or wait.
App. Config Add content
<connectionStrings> <add name="blogcontext" connectionstring= " Data source= (LocalDB) \v11.0; Attachdbfilename=d:\schoolwork\ software \ Database Connection \codefirstnewdatabasesample\codefirstnewdatabasesample\blogdatamdf.mdf ; Integrated security=true" providerName="System.Data.SqlClient " /> </connectionStrings>
String source
Entity Framework Connection string