ADO.NET Linq一对多选择用户ID

时间:2012-05-19 12:43:28

标签: linq entity-framework

首先踩堆栈溢出,我会尽力做到最好..

下面,我的模型来自ADO.NET(mysql数据库)

http://img585.imageshack.us/img585/4533/screenshot20120519at143.png

// CHECK USER+PASS
rmEntities2 myDb = new rmEntities2();
var query = from c in myDb.users
            where c.use_login == run.name
            where c.use_password == run.pass
            select c.use_id;

if (query.Count() == 0)
{
    return "ERROR USER/PASSWORD";
}
else
{
    // Linq insert DB
    running newRun = new running();
    newRun.run_start_time = new System.DateTime(1970, 1, 1, 0, 0, 0, 0)
        .AddSeconds(Double.Parse(run.start));
    newRun.run_end_time = new System.DateTime(1970, 1, 1, 0, 0, 0, 0)
        .AddSeconds(Double.Parse(run.stop));
    newRun.run_distance = (float)run.distance;
    newRun.run_nbfootsteps = run.nbfootsteps;
    newRun.run_vo2max = run.vo2Max;

    foreach (int u in query)
    {
        newRun.user.use_id = u;
    }

    myDb.AddTorunnings(newRun);
    myDb.SaveChanges();
    return "RUNNING ADDED";
}

问题出在这一行:

newRun.user.use_id = u;

我想在运行表中设置用户的run_use_id。

最好的方法是什么?

1 个答案:

答案 0 :(得分:2)

我希望您尝试在行中设置use_id

newRun.user.use_id = u;

你得到的是NullReferenceException。这是因为newRun.user为null - 新运行不与用户关联。

我建议您不要使用use_id,而应使用user

var query = from c in myDb.users
            where c.use_login == run.name
            where c.use_password == run.pass
            select c;
var user = query.SingleOrDefault();

然后是其中之一:

newRun.user = user; 
// or 
user.runnings.Add(newRun);

他们都做同样的事情,但使用对你更有意义的事情。