if record exists delete it? - c#

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();

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);

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();
}
}

Related

How to leave existing data unchanged is a condition is false

I am currently working on a project where I need to be able to rent a truck to a customer but also need to add the customer details if not existing. My problem is even though through the WPF form I input the exact same details of a customer, there would be a new set of data added thus creating a new Customer ID for one person. How would I be able to get the database disregard the existing customer details?
My data service code:
public class DataService
{
public static void rentTruck(TruckRental toRent, bool isNewCustomer)
{
using (var ctx = new DAD_TruckRental_RGMContext())
{
if (!isNewCustomer)
{
ctx.Entry(toRent.Customer).State = EntityState.Unchanged;//doesnt leave existing customer unchanged
}
ctx.Entry(toRent.Truck).State = EntityState.Modified;
ctx.TruckRental.Add(toRent);
ctx.SaveChanges();
}
}
My cs code:
private void Button_Click(object sender, RoutedEventArgs e)
{
TruckCustomer cust = new TruckCustomer();
cust.Age = int.Parse(ageTextBox.Text);
cust.LicenseNumber = licenseNumberTextBox.Text;
cust.LicenseExpiryDate = licenseExpiryDateDatePicker.SelectedDate.Value.Date;
TruckPerson per = new TruckPerson();
per.Address = addressTextBox.Text;
per.Telephone = telephoneTextBox.Text;
per.Name = nameTextBox.Text;
cust.Customer = per;
int truckId = int.Parse(truckIdTextBox.Text);
IndividualTruck truck = DataService.searchTruckByID(truckId);
decimal priceTotal = decimal.Parse(totalPriceTextBox.Text);
TruckRental toRent = new TruckRental();
toRent.TotalPrice = priceTotal;
toRent.RentDate = rentDateDatePicker.SelectedDate.Value.Date;
toRent.ReturnDueDate = returnDueDateDatePicker.SelectedDate.Value.Date;
toRent.Customer = cust;
toRent.Truck = truck;
truck.Status = "Rented";
DataService.rentTruck(toRent, true);
MessageBox.Show("Truck rented succesfully");
}
Here is my suggestion
1- First check if customer details already exist in db using LicenseNumber
2- The first step will be either null or have details, so if null then add received customer details otherwise update
here is the code
public class DataService
{
public static void rentTruck(TruckRental toRent, bool isNewCustomer, TruckCustomer tcustomer)
{
using (var ctx = new DAD_TruckRental_RGMContext())
{
var ob = ctx.TruckCustomer.Where(c => c.LicenseNumber == customer.LicenseNumber);
if ( ob != null) //not exist
{
//create new here
ctx.TruckCustomer.Add(tcustomer);
}
//exist then just update State
ctx.ob.State = EntityState.Modified;
ctx.AddOrUpdate(ob);
ctx.TruckRental.Add(toRent);
ctx.SaveChanges();
}
}
I hope this can help you

C# LinqToSql SubmitChanges() does not update, even though PK is set

I have the following code:
public int DeActivate(User entity) {
try {
using (UsersDataContext usersDC = new UsersDataContext()) {
users user = new users();
user = usersDC.users.Where(x => x.id == entity.Id).
Select(x => new users {active = x.active}).FirstOrDefault();
//user.active = entity.Active;
user.active = false;
usersDC.SubmitChanges();
return 1;
}
}
catch {
return 0;
}
}
While running an NUnit test on the method, the method returns 1, as it is supposed to do, and while de-bugging no exceptions are thrown. But, when i cross check with the DB the records have not being affected. I have tried the following: Re-created DBML file, checked for existance of PK, and checked the following sites:
MSDN question, StackOverflow question, but to no avail.
Your select statement is wrong. Try this.
public int DeActivate(User entity) {
try {
using (UsersDataContext usersDC = new UsersDataContext()) {
var user = usersDC.users.Single(x => x.id == entity.Id);
user.active = false;
usersDC.SubmitChanges();
return 1;
}
} catch {
return 0;
}
}

Update variable in foreach

I have an issue related to updating an object by reference and not sure exactly what is going on.
I need to delete a list of rules and for logging I need to load another field
ruleItem.ReferencedItemValue = eventEntity.Title;
When
builder.LogDelete(showRule, showRuleResource.ToAuditLog(), "Logic Rule");
is called the ReferencedItemValue is not populated.
Any ideas, suggestions, alternatives?
Thanks
CODE:
public void DeleteCustomLogicRule(int[] ruleIds){
var rules = uow.Context.ShowRules.Where(sr => ruleIds.Contains(sr.Id)).ToList();
if (rules.Any())
{
var showId = rules.FirstOrDefault().ShowId;
var builder = AuditBuilder.FromShowId(showId);
rules.ForEach(showRule =>
{
var showRuleResource = ToShowRuleResource(showRule);
FillReferenceValue(showRuleResource);
builder.LogDelete(showRule, showRuleResource.ToAuditLog(), "Logic Rule");
});
uow.Context.SaveChanges();
builder.ToDatabase();
}
}
private void FillReferenceValue(ShowRuleResource showRuleResource)
{
foreach (var ruleItem in showRuleResource.ItemsPredicateAppliesTo.ToList())
{
FillRuleItem(ruleItem);
}
}
private void FillRuleItem(RuleItemResource ruleItem)
{
var eventEntity = uow.Context.Events.FirstOrDefault(e => e.Id == ruleItem.ReferencedItemId.Value);
if (eventEntity != null)
ruleItem.ReferencedItemValue = eventEntity.Title;
}
try this one:
rules.ForEach(showRule =>
{
var item = showRule;
var showRuleResource = ToShowRuleResource(item);
FillReferenceValue(showRuleResource);
builder.LogDelete(item, showRuleResource.ToAuditLog(), "Logic Rule");
});
Start to dig from this function
private void FillRuleItem(RuleItemResource ruleItem)
It seems like this exspressiion
var eventEntity = uow.Context.Events.FirstOrDefault(e => e.Id == ruleItem.ReferencedItemId.Value);
is null.

Does EF upsert have to be done manually?

I want to upsert reference members of an existing entity.
Do I have to write specific code for the upsert?
meaning: I have to check if I'm handling an existing reference member or a new one.
Is there any other simple way to do so?
What happens when you do only Save ?
public void SaveCofiguration(MamConfiguration_V1Ui itemUi)
{
var itemEf = mMamConfiguration_V1UiToEfConvertor.ConvertToNewEf(itemUi);
using (var maMDBEntities = new MaMDBEntities())
{
IDal<MamConfiguration_V1> mamConfigurationDal = mDalFactory.GetDal<MamConfiguration_V1>(maMDBEntities);
mamConfigurationDal.Save(itemEf);
}
}
public MamConfiguration_V1 GetById(object id)
{
id.ThrowIfNull("id");
int configurationId = Convert.ToInt32(id);
var result =
mMaMDBEntities.MamConfiguration_V1.SingleOrDefault(item => item.ConfigurationId == configurationId);
return result;
}
public MamConfiguration_V1 Save(MamConfiguration_V1 item)
{
item.ThrowIfNull("item");
var itemFromDB = GetById(item.ConfigurationId);
if (itemFromDB != null)
{
UpdateEfItem(itemFromDB, item);
// if (mMaMDBEntities.ObjectStateManager.GetObjectStateEntry(itemFromDB).State == EntityState.Detached)
// {
// mMaMDBEntities.MamConfiguration_V1.AddObject(itemFromDB);
// }
// Attached object tracks modifications automatically
mMaMDBEntities.SaveChanges();
return item;
}
private void UpdateEfItem(MamConfiguration_V1 itemFromDb, MamConfiguration_V1 itemFromUi)
{
itemFromDb.UpdatedDate = DateTime.Now;
itemFromDb.Description = itemFromUi.Description;
itemFromDb.StatusId = itemFromUi.StatusId;
itemFromDb.Name = itemFromUi.Name;
itemFromDb.NumericTraffic = itemFromUi.NumericTraffic;
itemFromDb.PercentageTraffic = itemFromUi.PercentageTraffic;
itemFromDb.Type = itemFromUi.NumericTraffic;
foreach (var item in itemFromDb.MamConfigurationToBrowser_V1.ToList())
{
if (itemFromUi.MamConfigurationToBrowser_V1.All(b => b.BrowserVersionId != item.BrowserVersionId))
{
mMaMDBEntities.MamConfigurationToBrowser_V1.DeleteObject(item);
}
}
for (int i = 0; i < itemFromUi.MamConfigurationToBrowser_V1.Count; i++)
{
var element = itemFromUi.MamConfigurationToBrowser_V1.ElementAt(i);
var item = itemFromDb.MamConfigurationToBrowser_V1.SingleOrDefault(b => b.BrowserVersionId == element.BrowserVersionId);
if (item != null)
{
// copy properties from element to item
}
else
{
element.Browser = mMaMDBEntities.Browsers.Single(browserItem =>
browserItem.BrowserID == element.BrowserID);
//element.MamConfiguration_V1 = itemFromDb;
//have also tried: element.MamConfiguration_V1 = null;
//element.MamConfiguration_V1Reference = null;
itemFromDb.MamConfigurationToBrowser_V1.Add(element);
}
}
}
But I would have expecte Save(itemUi) and SaveChanges() to work fine. No?
public void InsertOrUpdate(DbContext context, UEntity entity)
{
context.Entry(entity).State = entity.Id == 0 ?
EntityState.Added :
EntityState.Modified;
context.SaveChanges();
}
http://forums.asp.net/t/1889944.aspx/1
To avoid the overhead of a query and then insert, or throwing exceptions, you can take advantage of the underlying database support for merges or upserts.
This nuget package does the job pretty well: https://www.nuget.org/packages/FlexLabs.EntityFrameworkCore.Upsert/
Github: https://github.com/artiomchi/FlexLabs.Upsert
Example:
DataContext.DailyVisits
.Upsert(new DailyVisit
{
// new entity path
UserID = userID,
Date = DateTime.UtcNow.Date,
Visits = 1,
})
// duplicate checking fields
.On(v => new { v.UserID, v.Date })
.WhenMatched((old, #new) => new DailyVisit
{
// merge / upsert path
Visits = old.Visits + 1,
})
.RunAsync();
The underlying generated sql does a proper upsert. This command runs right away and does not use change tracking, so that is one limitation.
See 'AddOrUpdate' method of System.Data.Entity.Migrations.
http://msdn.microsoft.com/en-us/library/system.data.entity.migrations.idbsetextensions.addorupdate%28v=vs.103%29.aspx
using System.Data.Entity.Migrations;
public void Save(Person person) {
var db = new MyDbContext();
db.People.AddOrUpdate(person);
db.SaveChanges();
}
"optimistic" approach for simple scenarios (demos)...
dbContext.Find()'s intellisense help tells us that it either retrieves entity by key if already present in current context, or queries the database to get it... then we know if it exists to either add or update. i'm using EFCore v2.2.0.
var existing = _context.Find<InventoryItem>(new object[] {item.ProductId});
if (existing == null) _context.Add(item);
else existing.Quantity = item.Quantity;
_context.SaveChanges();
DbContext.Update Method
For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Modified state. If the primary key value is not set then it will be tracked in the Added state. This helps ensure new entities will be inserted, while existing entities will be updated. An entity is considered to have its primary key value set if the primary key property is set to anything other than the CLR default for the property type.
For entity types without generated keys, the state set is always Modified.
read this article
you can use this sample

What is the Entity Framework equivalent of SQL UPDATE?

I looked all over the internet and still couldn't find a solution to this.
I tried the attach method:
public static void updatePhoto(string name, string albumName, string newName, string newPath)
{
//updates photo... no delete and adding...
var photo = new Image(){Label=newName, Path = newPath};
using (var db = new EzPrintsEntities())
{
db.Images.Attach(photo);
db.SaveChanges();
}
}
but that did not do anything at all.
So the question then is how do you implement an UPDATE to the sql database through EF in the code below?
public static void updatePhoto(string name, string albumName, string newName, string newPath)
{
EzPrintsEntities db = new EzPrintsEntities();
}
If you're updating an existing photo, you need to load it, and change the existing value:
public static void updatePhoto(string name, string albumName, string newName, string newPath)
{
using (var db = new EzPrintsEntities())
{
// Load photo
var photo = db.Images.FirstOrDefault(i => i.Label == name && i.Album == albumName);
if (photo == null)
{
// no matching photo - do something
}
// Update data
photo.Label = newName;
photo.Path = newPath;
db.SaveChanges();
}
}
The simplist way would be:
public static void updatePhoto(string name, string albumName, string newName, string newPath)
{
//updates photo... no delete and adding...
using (var db = new EzPrintsEntities())
{
var photo = (from p in db.Images
where p.name == name &&
p.albumname == albumName
select p).First();
photo.name = newName;
photo.path = newPath;
db.SaveChanges();
}
}
You simply select the existing photo object using Linq, modify it, and SaveChanges()
What you want to do is also pass to your updatePhoto method the value(s) for the primary key on your Image entity. Then instead of creating a new Image entity and attaching it and saving the context, you'll get the Image entity from your context, and just update the properties on it.
Something along these lines:
using (var db = new EzPrintsEntities())
{
var image = db.Images.SingleOrDefault(i => i.Id == id); // Assuming Id is the PK on Image, and we sent in the PK in a variable called id.
if (image != null)
{
image.Label = newName;
image.Path = newPath;
db.SaveChanges();
}
else
{
// Invalid PK value sent in, do something here (logging, error display, whatever).
}
}

Categories

Resources