我的項目中有兩個dummyrepositorys,一個用於提問,一個用於答案。問題是多重選擇,所以他們可以有多個答案。我問題型號:dummyrepository數據外鍵與隨機ID
public class Question : BaseClass
{
public Question() : base()
{
}
public int QuestionId { get; set; }
public string Value { get; set; }
public virtual List<Answer> Answers { get; set; }
}
而一個回答屬於問題
public class Answer : BaseClass
{
public Answer() : base()
{
}
public int AnswerId { get; set; }
public string Value { get; set; }
public int QuestionId { get; set; }
public virtual Question Question { get; set; }
}
他們都延長BaseClass的其中有一些自定義字段。
public abstract class BaseClass
{
protected BaseClass()
{
UniqueIdentifier = RandomIdentifier(20);
}
public string UniqueIdentifier { get; set; }
private static string RandomIdentifier(int length)
{
//returns an unique identifier
}
}
我dummyQuestionRepository樣子:
public class DummyQuestionRepository : IQuestionRepository
{
private List<Question> _questions;
public DummyQuestionRepository()
{
_questions = new List<Question>();
_questions.Add(new Question { Value = "Favourit food?" });
_questions.Add(new Question { Value = "Who is the president?" });
_questions.Add(new Question { Value = "Favourit movie?" });
}
public List<Question> GetAll()
{
return _questions;
}
public void Create(Question q)
{
_questions.Add(q);
}
//removed the non relevant functions
}
我dummyAnswerRepository
class DummyAnswerRepository
{
private List<Answer> _answers;
public DummyAnswerRepository()
{
_answers = new List<Answer>();
_answers.Add(new Answer { Value = "pizza" });
_answers.Add(new Answer { Value = "fries" });
_answers.Add(new Answer { Value = "Bush" });
_answers.Add(new Answer { Value = "Obama" });
_answers.Add(new Answer { Value = "titanic" });
_answers.Add(new Answer { Value = "lion king" });
}
public List<Answer> GetAll()
{
return _answers;
}
public void Create(Answer a)
{
_answers.Add(a);
}
}
正如你可能已經注意到了基類有一個唯一標識符的變量。此變量用於在聯機數據庫中創建唯一值(由於用戶在離線工作時可能使用相同的ID,因此無法使用該id),則應將UniqueIdentifier作爲有問題的外鍵。 我應該如何從問題中獲得/設置答案,以便我可以將它們加載到我的視圖中?
:只要刪除其創建的存儲庫的構造和使用代碼的新實體像下面的代碼。當您離線時,必須爲添加的任何新項目創建一個臨時ID。然後,當您連接到在線數據庫時,必須獲取永久ID,然後您必須用永久ID替換臨時ID。 – jdweng
@jdweng我真的很想使用我發佈的代碼。我不需要記住它是否同步的值以及需要在服務器的回調中設置id的值。我可能會更改代碼,但我仍然想知道如何解決我發佈的問題。 –
在線數據庫是否被一個或多個用戶使用?在線連接時如何獲得ID?當多個用戶使用數據庫時,您必須確保爲每個新項目生成唯一的ID。在解決同步問題之前,您首先必須解決此問題。 – jdweng