dotnet / EntityFramework.Docs

Documentation for Entity Framework Core and Entity Framework 6
https://docs.microsoft.com/ef/
Creative Commons Attribution 4.0 International
1.63k stars 1.96k forks source link

Document when the SQLite database needs to be configured for copying to the output directory #2261

Open dgroh opened 4 years ago

dgroh commented 4 years ago

I'm trying to implement the code based on console application sample but in WPF and I get the following error:

image

I've added the migration and updated the database. This is how my DbContext looks like:

    public class SettingsDbContext : DbContext
    {
        public DbSet<UserSettings> UserSettings { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder options)
            => options.UseSqlite("Data Source=settings.db");

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Client1Credentials>(c =>
            {
                c.HasNoKey();
                c.Property(p => p.Username);
                c.Property(p => p.Password);
            });

            modelBuilder.Entity<Client2Credentials>(c =>
            {
                c.HasNoKey();
                c.Property(p => p.Username);
                c.Property(p => p.Password);
            });
        }
    }

Here is how my Model looks like:

    public class UserSettings
    {
        public int Id { get; set; }

        public bool RememberCredentials { get; set; }

        [NotMapped]
        public Client1Credentials Client1Credentials { get; set; }

        [NotMapped]
        public Client2Credentials Client2Credentials { get; set; }
    }

Below you can see that the migration and database were created:

image


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

ajcvickers commented 4 years ago

@dgroh It looks like the current directory is different at runtime and hence the app isn't finding the SQLite database file. Try deploying to the current directory of the app at runtime, or being more explicit about the path to the file in the connection string.

dgroh commented 4 years ago

Hi @ajcvickers thanks. I figured it out. The trick was to make the .db file to Copy if newer or Copy always in the File properties -> Copy to output directory . I could not see this in the documentation.

ajcvickers commented 4 years ago

Note from team discussion: this step isn't needed for ASP.NET Core, but is for other targets such as WPF.

bricelam commented 4 years ago

See also https://github.com/dotnet/efcore/issues/18624