繁体   English   中英

如何使用实体框架将数据读/写到没有主键的表

[英]How to read/write data to a table which does not have a primary key using Entity Framwork

我是 ASP.NET MVC 和实体框架的整个概念的新手,并且一直面临从没有主键的现有表中读取数据的问题。

下面是数据库中的表,我猜它们彼此也不相关。 由于我不允许编辑现有表,我应该创建一个模型类来补偿缺失的因素。

dbo.SURVEY :我的应用程序只从这里读取数据。

int id [PK]
string title

dbo.QUESTIONS :我的应用程序只从这里读取数据。

int survey_id
int id [PK]
string text
string question_type (stores string values which says whether the question is an MCQ or has Text response)

dbo.OPTIONS :我的应用程序只从这里读取数据。

int ID [PK]
int question_id
string text

dbo.ATTEMPTED_ANSWER :我的应用程序根据用户输入读取和写入该表的数据。

int question_id
int answered_option_id (Has null values)
string answered_text

以下是我用于上述表格的模型类。

public class SURVEY
{
    public int id { get; set; }
    public string title { get; set; }

    public IList<QUESTIONS> Questions { get; set; }
}

public class QUESTIONS
{
    public int id { get; set; }

    [ForeignKey("Survey")]
    public int survey_id { get; set; }
    public string text { get; set; }
    public string answer_type { get; set; }

    public SURVEY Survey { get; set; }
    public IList<OPTIONS> Options { get; set; }
    public IList<ATTEMPTED_ANSWER> Attempted_Answers { get; set; }
}

public class OPTIONS
{
    public int id { get; set; }

    [ForeignKey("Question")]
    public int question_id { get; set; }
    public string text { get; set; }

    public QUESTIONS Question { get; set; }
}

public class ATTEMPTED_ANSWER
{
    [Key]
    public int id { get; set; } //has been created in the model does not exist in db

    [ForeignKey("Question")]
    public int question_id { get; set; }
    public int attempted_option_id { get; set; }
    public string attempted_text { get; set; }

    public QUESTIONS Question { get; set; }
}

这就是我迄今为止所管理的。

当我尝试使用以下代码存储与问题相关的所有条目时

var QuestionList =  _context.Questions
                            .Where(m => m.survey_id == id)
                            .Include(m => m.Options)
                            .Include(m => m.Attempted_Answers); //load question with related options and answers ```

我收到一个错误:

SqlException: 无效的列名“id”。

它没有显示此代码的错误:

var QuestionList =  _context.Questions
                            .Where(m => m.survey_id == id)
                            .Include(m => m.Options)

我知道错误与 id 属性有关,所以有人可以帮我解决这个问题吗? 有没有办法在自动设置我的 ATTEMPTED_ANSWER 实体的 id 属性的同时从数据库加载相关数据?

所以我最终创建了一个带有主键的新表。 对于这种情况,没有明确的解决方法可以让您有效地读取和写入数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM