[UWP] [EF] How to deal with database in specified folder

BitSmithy 2,226 Reputation points
2020-03-10T13:45:04.28+00:00

Hello,

In my UWP app I create a folder:

StorageFolder appFolder = ApplicationData.Current.LocalFolder;
databaseFolder = await appFolder.CreateFolderAsync(databaseFolderName, CreationCollisionOption.OpenIfExists);

now I use EF to deal with my SQLite database

public class myDbContext : DbContext   
{  
	public DbSet<MyClass> MyClasses{ get; set; }  
}  
  1. How to create a new database in "databaseFolder"
  2. How to connect to database stored in "databaseFolder"

I read a lot of docs about EF, but I couldnt find answer on this question.

Developer technologies | Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Answer accepted by question author
  1. Xiaodi Yan 881 Reputation points MVP
    2020-03-10T20:29:34.66+00:00

    From MS Docs:

    Connection strings in a UWP application are typically a SQLite connection that just specifies a local filename. They typically do not contain sensitive information, and do not need to be changed as an application is deployed. As such, these connection strings are usually fine to be left in code, as shown below. If you wish to move them out of code then UWP supports the concept of settings, see the App Settings section of the UWP documentation for details.

    public class BloggingContext : DbContext  
    {  
        public DbSet<Blog> Blogs { get; set; }  
        public DbSet<Post> Posts { get; set; }  
      
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
        {  
                optionsBuilder.UseSqlite("Data Source=blogging.db");  
        }  
    }  
    

    FYI: https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-strings

    I think you just need t change the connection string to your file path, eg.

    optionsBuilder.UseSqlite("Data Source=yourDbFolderName/yourDbName.db");  
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.