简体   繁体   English

C#实体框架+ SQLite-按用户选择数据库文件。

[英]C# Entity Framework + SQLite - selecting database file by user.

I made WPF app which uses Entity Framework and SQLite. 我制作了使用实体框架和SQLite的WPF应用程序。 At the beggining I loaded my database via ADO.NET Entity Data Model. 在开始时,我通过ADO.NET实体数据模型加载了数据库。 Everything was working quite good but now I want to add option for users to choose from local files with database (all tables in databases should be the same but data could be diffrent for diffrent files). 一切工作都很好,但是现在我想为用户添加选项以从具有数据库的本地文件中进行选择(数据库中的所有表应相同,但不同文件的数据可能有所不同)。 So to test this solution I copied my database file and made some changes in code: 因此,为了测试该解决方案,我复制了数据库文件并进行了一些代码更改:

I edited DbContext file by adding: (I found this here https://stackoverflow.com/a/23105811 ) 我通过添加以下内容编辑了DbContext文件:(我在这里https://stackoverflow.com/a/23105811找到了它)

    public appDBEntities(string filename)
     : base(new SQLiteConnection() { ConnectionString =
        new SQLiteConnectionStringBuilder()
            { DataSource = filename, ForeignKeys = true }
        .ConnectionString }, true)
    {
    }

The users is selecting database file by using this function: 用户正在使用此功能选择数据库文件:

    private void testButton_Click(object sender, RoutedEventArgs e)
    {
        // Create OpenFileDialog 
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

        // Set filter for file extension and default file extension 
        dlg.DefaultExt = ".db";
        dlg.Filter = "Database files (*.db)|*.db";

        // Display OpenFileDialog by calling ShowDialog method 
        Nullable<bool> result = dlg.ShowDialog();

        // Get the selected file name
        if (result == true)
        {
            // Open document 
            publicVariables.databasePath = dlg.FileName;
        } 
    }

Than i want to test if everything is ok by displaying some data from database with this function: 比我想通过使用此功能显示数据库中的一些数据来测试一切是否正常:

    public static void showParticipants(DataGrid participantsDataGrid, string connectionString)
    {
        using (var db = new appDBEntities(connectionString))
        {
            var query = from c in db.Participant
                        join gender in db.Sex on c.Sex equals gender.id
                        join club in db.Club on c.Club equals club.id
                        join nation in db.Nation on c.Nationality equals nation.id
                        select c.id;

            var data = query.ToList();
            participantsDataGrid.ItemsSource = data;
            db.Dispose();
        }

    }

Like this: 像这样:

showParticipants(testDataGrid, publicVariables.databasePath);

But this function 但是这个功能

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

Is throwing this exception: 抛出此异常:

The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. 上下文在Code First模式下与从EDMX文件生成的代码一起用于Database First或Model First开发。 This will not work correctly. 这将无法正常工作。 To fix this problem do not remove the line of code that throws this exception. 若要解决此问题,请不要删除引发此异常的代码行。 If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. 如果希望使用数据库优先或模型优先,请确保在启动项目的app.config或web.config中包含Entity Framework连接字符串。 If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. 如果要创建自己的DbConnection,请确保它是EntityConnection而不是其他某种类型的DbConnection,并将其传递给采用DbConnection的基本DbContext构造函数之一。 To learn more about Code First, Database First, and Model First see the Entity Framework documentation >here: http://go.microsoft.com/fwlink/?LinkId=394715 要了解有关“代码优先”,“数据库优先”和“模型优先”的更多信息,请参见Entity Framework文档>此处: http : //go.microsoft.com/fwlink/?LinkId=394715

I have a similar task working by changing config entry, maybe it would work for you: 我有一个类似的任务可以通过更改配置条目来工作,也许对您有用:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");

connectionStringsSection.ConnectionStrings["DbStatisticsEntities"].ConnectionString =
    "metadata=res://*/Models.DbStatisticsModel.csdl|res://*/Models.DbStatisticsModel.ssdl|res://*/Models.DbStatisticsModel.msl;provider=System.Data.SQLite.EF6;provider connection string='data source=" + this.DBFileName + "'";
connectionStringsSection.ConnectionStrings["DbStatisticsEntities"].ProviderName = "System.Data.EntityClient";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");

Properties.Settings.Default.Save();
Properties.Settings.Default.Reload();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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