简体   繁体   English

更新记录在LINQ to SQL中不起作用

[英]Updating record not working in LINQ to SQL

I have this sequence generation query that gets the current sequence and increment it to next value. 我有这个序列生成查询,它获取当前序列并将其增加到下一个值。 But the increment is not updating. 但增量不是更新。 The nextval is always returning 1, the default value from the database nextval始终返回1,即数据库中的默认值

Entity  | StartVal | Increment | CurVal | NextVal
----------------------------------------------------
INVOICE |   0      |     1     |   0    |   1

The nextval should be 3, 5, 7 and so on nextval应该是3,5,7等等

int nextVal = 0;
using (var db = new MedicStoreDataContext())
{
    DAL.LINQ.Sequence seq = (from sq in db.Sequences
                where sq.Entity == entity
                select sq).SingleOrDefault();

    if (seq != null)
    {
        nextVal = seq.NextVal.HasValue ? seq.NextVal.Value : 0;


        seq.NextVal = nextVal + 2;

        db.SubmitChanges();
    }

}

Have I left something undone? 我是否遗失了一些东西?

UPDATE: Answer: I needed to set the Primary Key and update Sequence class field to include the Primary Key 更新:答案:我需要设置主键并更新序列类字段以包含主键

Usually this is because it hasnt found the unique identifier (or Primary Key) for a table. 通常这是因为它没有找到表的唯一标识符(或主键)。

In your data descriptions are you sure the table correctly picked up the unique item? 在您的数据描述中,您确定表格是否正确选取了唯一的项目? - when I first tried this although I had a unique key etc, the table description in c# didnt mark it as unique, so the linq quietly didnt updated it as I had expected, no errors no warnings. - 当我第一次尝试这个时虽然我有一个唯一的密钥等,但是c#中的表描述没有将它标记为唯一,所以linq悄悄没有像我预期的那样更新它,没有错误没有警告。 Once I corrected the data table in c#, it all went well. 一旦我在c#中更正了数据表,一切都进展顺利。

Isn't that the correct behaviour? 这不是正确的行为吗? wouldn't you expect nextVal to be 1 if CurVal is 0? 如果CurVal为0,你不期望nextVal为1吗? I may be missing something here but it seems like your overcomplicating it a bit. 我可能在这里遗漏了一些东西,但似乎你有点过分复杂了。 Isn't what you want to do basically 不是你想要做的基本上

using (var db = new MedicStoreDataContext())
{
    DAL.LINQ.Sequence seq = (from sq in db.Sequences
                where sq.Entity == entity
                select sq).SingleOrDefault();

    if (seq != null)
    {
        seq.CurVal += seq.Increment;

        db.SubmitChanges();
    }
}

I don't see why you need the whole nextVal bit at all. 我不明白为什么你需要整个nextVal位。 Please feel free to correct me if I'm wrong. 如果我错了,请随时纠正我。

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

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