How to import database files into a solution for a C # console application that uses the Entity Framework

I created a console application in C #. I installed the Entity Framework NuGet for this solution.

I have a class Person:

  public class Person {

        public int Id { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public DateTime BirthDate { get; set; }
    }

I created a db context:

  public class ApplicationDbContext : DbContext {

        public ApplicationDbContext()
        : base("MiniProjekt") { }
        public DbSet<Person> Persons { get; set; }
    }

Included migrations in the package manager console. The database connection is working. I get valid data for the code below (I inserted some objects before), but I don't know where the database is.

    static void Main(string[] args) {
        var context = new ApplicationDbContext();
        Console.WriteLine(context.Persons.Count());
        foreach (Person person in context.Persons) {
            Console.WriteLine(person.LastName);
        }
        Console.ReadKey();
    }

The problem is that I do not know where the .mdffile with my database is located. I clicked "Show all files in Solution Explorer", looked at the project files, and I can not find it. I want to send this project later by mail, and I would like to save the database file in the solution.

: , (, ASP.NET-MVC).

EDIT: , :

enter image description here

+4
1

, localdb. Visual Studio, : VIEW > SQL Server > SQL Server > (localdb). .

, , , . . . c:\Users\YourUserName \, .mdf .ldf.

Edit:

.

  • .mdf . , > > ... > > , .

    Data, . , , ; ", " " " .

  • (app.config) . , Entity .

  • :

    <connectionStrings>
      <add name="YourContextClassName" connectionString="Server=(localdb)\ProjectsV12;Integrated Security=true;AttachDbFileName=|DataDirectory|YourDatabase.mdf;" providerName="System.Data.SqlClient" />
    </connectionStrings>
    

    YourContextClassName: DbContext.

    (localdb)\ProjectsV12: SQL- localdb. localdb .

    YourDatabase.mdf: mdf, / 1.

  • DataDirectory:

    static YourContextClassName()
    {
        var baseDir = AppDomain.CurrentDomain.BaseDirectory;
        // You might Path.Combine(baseDir, "Data") here, if you want to have a
        // data subdirectory.
        var fullPath = Path.GetFullPath(baseDir);
        AppDomain.CurrentDomain.SetData("DataDirectory", fullPath);
    }
    

    , | DataDirectory | .

  • LocalDB. , LocalDB - . MSDN .

  • Profit.

+4

Source: https://habr.com/ru/post/1569444/


All Articles