Reputation: 3945
I am using this code to create a record in the ClientAccountAccess table. However there should only ever be one record in this table at any time. so if this function is called I first want to check if a record exists, if it does delete it then add the new record.
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();
Upvotes: 1
Views: 1191
Reputation: 31239
Do you really need to remove it? If you don't you can do this:
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();
}
}
Then you will only insert it if it do not already exists
If you need to remove it before creating the object. You can do this:
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();
}
}
If you can update the object you can do something like this:
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();
}
}
Upvotes: 1
Reputation: 9725
Try something like this...
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);
Upvotes: 1