1

这是我的课:

[Table]
public class Question
{
    [Column]
    public bool Sort { get; set; }
    [Column(IsPrimaryKey = true)]
    public int QuestionID { get; set; }
    [Column]
    public int Level { get; set; }
    [Column]
    public string Description { get; set; }
    [Column]
    public string Answer1 { get; set; }
    [Column]
    public string Answer2 { get; set; }
    [Column]
    public string Answer3 { get; set; }
    [Column]
    public string Answer4 { get; set; }
    [Column]
    public string RightAnswer { get; set; }
    [Column]
    public bool Show { get; set; }
}

public class QuestionContext : DataContext
{
    public QuestionContext(string connectionString)
        : base(connectionString)
    {
    }
    public Table<Question> Questions
    {
        get
        {
            return this.GetTable<Question>();
        }
    }
}

我正在尝试连接到我现有的数据库:

 private const string ConnectionString = @"appdata:App_Data\QuestionDb.sdf";

public GamePage()
{
    InitializeComponent();

    using (QuestionContext context = new QuestionContext(ConnectionString))
    {

        if (!context.DatabaseExists())
        {
            // create database if it does not exist
            context.CreateDatabase();
        }
        else
        {
            var questions = from o in context.Questions where o.Level == 1 && o.Show == false select o;
            var question = questions.FirstOrDefault();
        }
    }
}

我收到“不允许访问数据库文件”的错误。我认为问题出在我的连接字符串中。它出什么问题了?如何访问文件夹 App_Data 中的 SQLCE 数据库?

4

2 回答 2

1

在您的 app.config 中添加以下内容

<connectionStrings>
  <add name="DataContext" 
       connectionString="Data source=DataDirectory|Database.sdf;"
       providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>

然后在 ConfigurationManager 的帮助下获取连接字符串。也许您需要添加对 System.Configuration 的引用。

private const string ConnectionString = ConfigurationManager.ConnectionStrings["DataContext"].ConnectionString

您可以在此处了解有关 ConnectionString 中的 DataDirectory 的更多信息:http: //msdn.microsoft.com/en-us/library/cc716756 (v=vs.100).aspx

于 2012-12-23T12:02:30.837 回答
0

您必须像这样编写连接字符串:

MyDataContext db = new MyDataContext("Data Source = 'appdata:/mydb.sdf'; File Mode = read only;");

数据库文件将是只读的...

于 2012-12-23T13:46:30.243 回答