增加或更新实体框架的金额

时间:2013-08-09 22:18:00

标签: c# mysql entity-framework

我该如何翻译:

INSERT INTO test (id, amount) VALUES(1, 5) 
ON DUPLICATE KEY 
UPDATE amount=amount + VALUES(amount)  

使用mysql查询进入Entity Framework?

2 个答案:

答案 0 :(得分:2)

提取逻辑。如manual中所述:

  

如果指定ON DUPLICATE KEY UPDATE,并且插入的行将导致UNIQUE索引或PRIMARY KEY中出现重复值,则执行旧行的UPDATE。例如,如果列a声明为UNIQUE并且包含值1,则以下两个语句具有相同的效果:

INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;    

// And

UPDATE table SET c=c+1 WHERE a=1;

您的查询说:插入一行ID为1且金额为5的行,但如果存在,请将ID为1的行数增加5.

据我所知,MS-SQL不支持这样的声明,所以你必须自己完成这项工作:

public void InsertOrUpdateTest(Test input)
{
    var entity = _dbContext.Test.FirstOrDefault(t => t.ID == input.ID);

    // If that record doesn't exist, create it and add it to the DbSet<Test> Tests
    if (entity== null)
    {
        entity= new Test(id = input.ID);
        _dbContext.Tests.Add(entity);
    }

    // Increase the amount. For a new entity this will be equal to the amount,
    // whereas an already existing entitiy gets its current value updated.
    entity.Amount += input.Amount;

    _dbContext.SaveChanges();
}

答案 1 :(得分:1)

您可以尝试这样的事情:

var id = 1;
var amount = 5;

var existing = db.Test.SingleOrDefault(x => x.Id == id);

if (existing != null)
{
    existing.Amount = existing.Amount + amount;
}
else 
{
    db.Test.Add(new Test{Id=id,Amount=amount});
}

db.SaveChanges();