I'm trying out Vici CoolStorage with Monotouch and seem to be having an issue with relationships. Using the following I am trying to populate a database with a single Survey and then generate a list of 5 questions using a for loop.
When I run it there seems to be an issue mapping the Questions to the Survey in the database so if anyone could give me an idea of what I've missed it would be much appreciated! The error given is "Vici.CoolStorage.CSException: Relation Survey could not be read".
[MapTo("Survey")]
public class Survey : CSObject<Survey, int>
{
public int SurveyId { get { return (int)GetField ("SurveyId"); } }
public string Title { get { return (string)GetField ("Title"); } set { SetField ("Title", value); } }
public DateTime DateCreated { get { return (DateTime)GetField ("DateCreated"); } set { SetField ("DateCreated", value); } }
public bool IsCurrent { get { return (bool)GetField ("IsCurrent"); } set { SetField ("IsCurrent", value); } }
[OneToMany(LocalKey="SurveyId", ForeignKey="QuestionId")]
public CSList<Question> Questions { get { return (CSList<Question>)GetField("Questions"); } }
}
[MapTo("Question")]
public class Question : CSObject<Question, int>
{
public int QuestionId { get { return (int)GetField ("QuestionId"); } }
public string Text { get { return (string)GetField ("Text"); } set { SetField ("Text", value); } }
public int SurveyId { get { return (int)GetField ("SurveyId"); } }
[ManyToOne(LocalKey="QuestionId", ForeignKey="SurveyId")]
public Survey Survey { get { return (Survey)GetField ("Survey"); } set { SetField ("Survey", value); } }
}
CSDatabase.ExecuteNonQuery (@"CREATE TABLE Survey (SurveyId INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT(100) NOT NULL, DateCreated TEXT(50) NOT NULL, IsCurrent INTEGER)");
CSDatabase.ExecuteNonQuery (@"CREATE TABLE Question (QuestionId INTEGER PRIMARY KEY AUTOINCREMENT, Text TEXT(100) NOT NULL, SurveyId INTEGER REFERENCES Survey(SurveyId))");
for (int i = 1; i <= 10; i++)
{
Question q = Question.New ();
q.Text = String.Format ("Question {0}", i);
survey.Questions.Add (q);
}
survey.Save();
You haven't linked the correct foreign keys in your mapped fields. The relations should be declared as:
[OneToMany(LocalKey="SurveyId", ForeignKey="SurveyId")]
public CSList<Question> Questions ...
and
[ManyToOne(LocalKey="SurveyId", ForeignKey="SurveyId")]
public Survey Survey...