简体   繁体   中英

Entity Framework Code First no database in SQL Server Management Studio

I am trying to create a DB using EF code first. I did the following:

  • Created the classes
  • Created a data context using said classes
  • I used parameterless constructor on context class with :base("connectionstring")
  • I opened the Nuget Manager console and i typed the commands:

enable-migrations

add-migrations mydatabase

update-database

After doing this the folder with the migration files appeared in the solution explorer but the Database still doesn't appear in my SQL Server Management Studio

Below is the code:

1.Classes

public class Kid
{      
    public int KidId { get; set; }
    public int Age { get; set; }
    public string Name { get; set; }
}

[Table("School")]
public class School
{
    [Key]
    public int SchoolId { get; set; }
    public string SchoolName { get; set; }
    public List<Kid> Kids { get; set; }

}

public class SchoolContext:DbContext
{
    public  SchoolContext() : base("SchoolContext") { }
    public DbSet<Kid> Kid { get; set; }
    public DbSet<School> School { get; set; }
}

2.Main

class Program
{
    static void Main(string[] args)
    {
        SchoolContext myDb = new SchoolContext();
        Kid mykid = new Kid { Age = 14, KidId = 2, Name = "Adrian" };
        Kid mykid2 = new Kid { Age = 16, KidId = 3, Name = "Adriansan" };
        School mySchool = new School { Kids = new List<Kid>{ mykid, mykid2 }, SchoolId = 73, SchoolName = "Iovan Ducici" };
        myDb.Kid.Add(mykid);
        myDb.School.Add(mySchool);
        myDb.SaveChanges();
        Console.ReadLine();
    }
} 

I suspect there's something to be done in the App.config file which has a connectionString tag which is empty but I don't know what it has to be completed.

Generally you need to have a connection string in the app config that knows 'where' is your database created at. A context is just a blueprint to create the database that 'SchoolContext' should be referencing a connection string in an app config or similar to an actual project that runs the EF Code First

<connectionStrings>
   <add name="SchoolContext" providerName="System.Data.SqlClient" connectionString="Server=.;Database=SchoolContext;Integrated Security=True;"/>
</connectionStrings>

If you do not have this it will most likely not work. And since you do a lot of stuff manually with EF code first it may not show up. Or it may assume an MS default database which handles connections differently than MS SQL or it may be SQL Express.

I took this tutorial from this site a while back and it is fantastic for learning the ins and outs of the basics for EF Code First: http://www.entityframeworktutorial.net/code-first/entity-framework-code-first.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM