gpt4 book ai didi

C# EF Code first - 创建数据库和添加数据

转载 作者:行者123 更新时间:2023-11-30 15:36:09 25 4
gpt4 key购买 nike

我想创建数据库并添加一些数据。我添加了 EF,我想先使用代码。我有这些类(class):

public class Question
{
public bool Sort { get; set; }
public int QuestionID { get; set; }
public int Level { get; set; }
public string Description { get; set; }
public string Answer1 { get; set; }
public string Answer2 { get; set; }
public string Answer3 { get; set; }
public string Answer4 { get; set; }
public string RightAnswer { get; set; }
public bool Show { get; set; }
}

public class QuestionDb : DbContext
{
public DbSet<Question> Questions { get; set; }
}

这是我的连接字符串:

<add name="ConvertCSVtoSQL.QuestionDb" connectionString="Data Source=|DataDirectory|ConvertCSVtoSQL.QuestionDb.sdf"
providerName="System.Data.SqlServerCe.4.0" />

现在我正在创建这样的数据库:

using (var db = new QuestionDb())
{

foreach (var question in questions)
{
db.Questions.Add(question);
}
db.SaveChanges();
}

它会创建数据库,但如果我在问题中有一些数据要添加,我会收到错误消息:

The Entity Framework provider type 'System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' for the 'System.Data.SqlServerCe.4.0' ADO.NET provider could not be loaded. Make sure the provider assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.

我尝试添加一些初始值设定项,但没有帮助:

Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0",@"C:\Path\To\",@"Data Source=C:\Path\To\DbFile.sdf");
Database.SetInitializer(new CreateDatabaseIfNotExists<QuestionDb>());

那么问题出在哪里呢?

最佳答案

我查看了异常链接,将 nuget 包 EntityFramework.SqlServerCompact 添加到我的解决方案中,这很有帮助。

关于C# EF Code first - 创建数据库和添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13986758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com