If db already exists and filled with data we just can create Entities in code…
For example lets create db manually… in localdb of SQL Server
View->Server Explorer.
Next in serverName type “(localdb)\MSSQLLocalDB” for vs 2015 and choose new datebase or type new one and vs will suggest create new one
Next lets get connection string of our new db in localdb
1 |
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=someNewDB;Integrated Security=True |
Now put connection string to app.config
1 2 3 4 5 |
<connectionStrings> <add name="localdb_usersstoredb" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=someNewDB;Integrated Security=True" providerName="System.Data.SqlClient"/> <add name="localdb" connectionString="data source=(localdb)\MSSQLLocalDB;Initial Catalog=userstore.mdf;Integrated Security=True;" providerName="System.Data.SqlClient"/> <add name="localdb_usersstoredb" connectionString="data source=(localdb)\MSSQLLocalDB;Initial Catalog=userstoredb;Integrated Security=True;" providerName="System.Data.SqlClient"/> </connectionStrings> |
Now create new table
and add columns
Click Update and see
Update DataBase and start Editing some data
Now SolutionExplorer > Manage NuGetPackages for Solution > type Entity in search box and Install it to your project
Add using System.Data.Entity if not added before…
Lets write user class and userContext class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class User { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } class UserContext : DbContext { public UserContext() : base("localdb_usersstoredb") { } public DbSet<User> Users { get; set; } } |
In main lets check what is in our dataBase
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Program { static void Main(string[] args) { using (UserContext db = new UserContext()) { var users = db.Users; foreach (User u in users) { Console.WriteLine("{0}.{1} - {2}", u.Id, u.Name, u.Age); } } Console.Read(); } } |
Full code is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Entity; namespace CodeSecond { class Program { static void Main(string[] args) { using (UserContext db = new UserContext()) { var users = db.Users; foreach (User u in users) { Console.WriteLine("{0}.{1} - {2}", u.Id, u.Name, u.Age); } } Console.Read(); } } public class User { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } class UserContext : DbContext { public UserContext() : base("localdb_usersstoredb") { } public DbSet<User> Users { get; set; } } } |