如果记录存在删除它?

时间:2014-02-11 12:14:24

标签: c# asp.net-mvc asp.net-mvc-3

我正在使用此代码在ClientAccountAccess表中创建记录。但是,此表中任何时候都应该只有一条记录。因此,如果调用此函数,我首先要检查记录是否存在,如果删除它,则添加新记录。

     private static void SetAccessCode(string guidCode)
        {
            using (EPOSEntities db = new EPOSEntities())
            {

//so here would I say something like (see below)

                ClientAccountAccess client = new ClientAccountAccess();
                client.GUID = guidCode;
                db.AddToClientAccountAccesses(client);
                db.SaveChanges();
            }
        }

//
ClientAccountAccess clientAccessCodes = db.ClientAccountAccesses
                    .OrderByDescending(x => x.Id)
                    .Take(1)
                    .Single();

                if clientAccessCodes.exists()

                    db.DeleteObject(clientAccessCodes);
                db.SaveChanges();

2 个答案:

答案 0 :(得分:1)

尝试这样的事情......

bool doesItExistAlready = (from caa in db.ClientAccountAccesses
                           where css.id == guidCode
                           select caa).Any();

if (doesItExistAlready)
{
    // Delete old record
    db.DeleteObject(PUTIDENTIFIERHERE);
}

// Add new record
ClientAccountAccess client = new ClientAccountAccess();
client.GUID = guidCode;
db.AddToClientAccountAccesses(client);

答案 1 :(得分:1)

你真的需要删除吗?如果不这样做,你可以这样做:

private static void SetAccessCode(string guidCode)
{
    using (EPOSEntities db = new EPOSEntities())
    {
        var c= db.ClientAccountAccesses.FirstOrDefault(f=>f.GUID==guidCode);
        if(c!=null)
            return;
        var client = new ClientAccountAccess(){GUID=guidCode};
        db.AddToClientAccountAccesses(client);
        db.SaveChanges();
    }
}

然后,只有当它不存在时才会插入

如果需要在创建对象之前将其删除。你可以这样做:

private static void SetAccessCode(string guidCode)
{
    using (EPOSEntities db = new EPOSEntities())
    {
        var c= db.ClientAccountAccesses.FirstOrDefault(f=>f.GUID==guidCode);
        if(c!=null)
        {
            db.ClientAccountAccesses.DeleteObject(c);
            db.SaveChanges();
        }
        var client = new ClientAccountAccess(){GUID=guidCode};
        db.AddToClientAccountAccesses(client);
        db.SaveChanges();
    }
}

如果你可以更新对象,你可以这样做:

private static void SetAccessCode(string guidCode)
{
    using (EPOSEntities db = new EPOSEntities())
    {
        var c= db.ClientAccountAccesses.FirstOrDefault(f=>f.GUID==guidCode);
        if(c==null)
        {
            c=new ClientAccountAccess();
            db.AddToClientAccountAccesses(client);
        }
        c.GUID=guidCode;
        db.SaveChanges();
    }
}