WP7 - 不允许访问数据库文件

时间:2012-12-23 11:11:10

标签: c# database windows-phone-7 sql-server-ce

这是我的班级:

[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数据库?

2 个答案:

答案 0 :(得分:1)

在app.config中添加以下内容

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

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

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

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

答案 1 :(得分:0)

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

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

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