This is my class:
[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>();
}
}
}
I am trying to connect to my existing database:
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();
}
}
}
I get error with "Access to the database file is not allowed". I think problem is in my connection string. What's wrong with it? How can I get access to SQLCE database in folder App_Data?
In your app.config add the following
<connectionStrings>
<add name="DataContext"
connectionString="Data source=DataDirectory|Database.sdf;"
providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
Then get the connectionstring with help from ConfigurationManager. Maybe you need to add a reference to System.Configuration.
private const string ConnectionString = ConfigurationManager.ConnectionStrings["DataContext"].ConnectionString
You can learn more about DataDirectory in ConnectionString here: http://msdn.microsoft.com/en-us/library/cc716756(v=vs.100).aspx
You must compose the connection string like this:
MyDataContext db = new MyDataContext("Data Source = 'appdata:/mydb.sdf'; File Mode = read only;");
The database file will be read only...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.