从数据库获取数据到列表

时间:2018-10-25 12:08:24

标签: c# entity-framework model

我表中的数据在SQL中没有主键。在Entity Framework模型中,我将PK设置为acol(即使对于acol的某些值有多个行)。

数据存储如下

#include <mydata.hpp>

#include <QGuiApplication>
#include <QMap>
#include <QQmlApplicationEngine>
#include <QQmlComponent>
#include <QQmlContext>
#include <QQuickView>

#include <iostream>

int main(int argc, char *argv[])
{
    MyData test1("Hi");
    MyData test2("Hello");
    QMap<QString, QVariant> mymap; // QVariantMap

    QVariant qvtest1(test1); // error: no matching function for call to ‘QVariant::QVariant(MyData&)’

    //working:
    QVariant qvtest1, qvtest2;
    qvtest1.setValue(test1);
    qvtest2.setValue(test2);


    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    auto *engine = new QQmlEngine;
    QQuickView view;
    QQmlContext *ctxt = view.rootContext();

    // this is working:
    qmlRegisterType<MyData>("MyData", 1, 0, "MyData");
    engine->rootContext()->setContextProperty("test1", &test1);


    // this produces an error: calling a private constructor of class 'QVariant'
    engine->rootContext()->setContextProperty("mymap", &mymap);

    QQmlComponent component(engine, QUrl("qrc:/main.qml"));
    QQmlEngine::setObjectOwnership(engine, QQmlEngine::CppOwnership);
    QObject *object = component.create();

    return app.exec();
}

我有这样的查询

AAATable
    acol bcol 
    124   125 
    124   126

然后我循环进行数据记录

        var AAATableList = (from tdrc in db.AAATable
                                      where tdrc.acol == id
                                      select tdrc).ToList();

克劳斯(crouse),表中有2行,所以我在日志中写了2行,但是值写成如下

125

125

而不是125126

更新

foreach (var itemB in AAATableList) { Logger.WriteLog("AAATable.txt", itemB.bcol.ToString()); } 返回2

AAATable.Count()返回125

AAATable.First().bcol.ToString()返回124

AAATable.First().acol.ToString()返回125

AAATable.Last().bcol.ToString()返回124

这个想法是在循环foreach循环的同时获得125和126的值, 但是相反,我得到了125和125

2 个答案:

答案 0 :(得分:0)

  

,在Entity Framework模型中,我将PK设置为acol。所以也许那是   回答?

是的,这就是问题的原因。您告诉Entity Framework acol是一个PK,但是您的数据如下所示:

AAATable
    acol bcol 
    124   125 
    124   126

换句话说,您对Entity Framework撒了谎(您说每个值124只有一条记录),并且它是caught you所在。 :)

答案 1 :(得分:0)

我尝试了您的代码,它可以正常工作

只需确保在EF模型中将两个主键分别放在acolbcol

enter image description here

相关问题