could you help with this? I bet this isn't any tough one..but am new to EF and facing a weekend deadline. I want to update a table with values.. but the primary key is identity column. So my task is like this.. if it exists, update.. if it doesn't add to the
table.. this is my code..and am stuck in this else part..!
Table structure is like this
Primary Key table - System: SystemId, SystemName
Foreign Key table - SystemConfiguration: SystemConfigurationId, SystemId, SystemRAM, SystemHard-Disk
public void SaveSystemConfigurations(SystemConfiguration systemConfig)
{
var config = (from s in Context.SystemConfiguration
where s.SystemId == systemConfig.SystemId
select s).FirstOrDefault();
if (config == null)
{
Context.SystemConfigurations.AddObject(systemConfig);
Context.SaveChanges();
}
else
{
// EntityKey systemConfigKey= new EntityKey("systemConfig", "systemConfigId", config.SystemConfigurationId);
Context.SystemConfigurations.Attach(systemConfig);
Context.SaveChanges();
}
}
Try this:
public void SaveSystemConfigurations(SystemConfiguration systemConfig)
{
var config = (from s in Context.SystemConfiguration
where s.SystemId == systemConfig.SystemId
select s).FirstOrDefault();
if (config == null)
{
Context.SystemConfigurations.AddObject(systemConfig);
}
else
{
config.Attribute = value; // Do your update here
}
Context.SaveChanges();
}
Edit. It should be config not systemConfig.
The ApplyCurrentValues method will apply scalar attributes to an entity that matches the same key. My assumption is that you are modifying a real entity (an object that has a valid entity key).
This would work:
var eSet = config.EntityKey.EntitySetName;
Context.ApplyCurrentValues(eSet, systemConfig);
Context.SaveChanges();
public void SaveSystemConfigurations(SystemConfiguration systemConfig)
{
var context = new EntitiesModel();
//here is the name of the partial class created on the Context area of the edmx designer.cs
var config = (from s in context.SystemConfiguration
where s.SystemId == systemConfig.SystemId
select s).FirstOrDefault();
context.ApplyCurrentValues(config.EntityKey.EntitySetName, systemConfig);
// systemConfig comes from the view with values set by the user
// you dont have to manually need to map one value at the time
context.SaveChanges();
}
Related
I have a simple association table whose PK isn't referenced anywhere but when I am trying to delete a record from it in the following way, I get an error. I am using EF code-first. Any help would be very very helpful. Thanks in advance.
List<ViolationTypeNOV> novRels = UnitOfWork.Context.ViolationTypeNOVs.Where(x => x.NOVId == nov.NOVId).Include("ViolationType").Include("NOV").ToList();
foreach (ViolationTypeNOV o in novRels)
{
UnitOfWork.Context.ViolationTypeNOVs.Remove(o);
}
UnitOfWork.Context.SaveChanges();
Here is the error message I am getting. If the table's PK isn't referenced in any way, why is it failing with this error? Just not able to understand:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
The same thing if I am running through SSMS same thing is working though:
DELETE ViolationTypeNOVs
WHERE ViolationTypeNOVId = 2
Why?
But again if I am running the same query through context as below, I get the same error at the calling SaveChanges:
foreach (ViolationTypeNOV o in novRels)
{
string str = string.Format("Delete ViolationTypeNOVs where ViolationTypeNOVId = {0}", new object[] { o.ViolationTypeNOVId });
UnitOfWork.Context.Database.ExecuteSqlCommand(str);
}
UnitOfWork.Context.SaveChanges();
It seems like some of the objects within the context aren't nulling or getting deleted, is there anyway to clear them all in one go? Because these ids/objects are used in multiple places in the code - please let me know how to clear them all - thanks a lot.
Any help please?
Fixed it - the problem is we need to clear up all the objects and its links that the parent object is using then only we can save the changes thanks here is my solution
public bool Delete(NOV nov, bool performCommit = true)
{
System.Data.Entity.DbContextTransaction dbOperation = null;
if (performCommit)
dbOperation = UnitOfWork.BeginTransaction();
try
{
//-- Remove the Items - "foreach" approach was a problem
// http://weblogs.asp.net/ricardoperes/entity-framework-pitfalls-deleting-orphans
//------------------------------------------------------
// Remove the Violations that are in this NOV
//------------------------------------------------------
List<Violation> violationIdlist = new List<Violation>();
foreach (var v in nov.ViolationNOVs)
{
var a = UnitOfWork.ViolationRepository.GetAll().Where(z => z.ViolationId == v.ViolationId).FirstOrDefault();
violationIdlist.Add(a);
}
foreach (var v in violationIdlist)
{
var a = nov.ViolationNOVs.Where(x => x.NOVId == nov.NOVId && x.ViolationId == v.ViolationId)?.FirstOrDefault();
nov.ViolationNOVs.Remove(a);
}
nov.IssuedBy.Clear();
//deleting all OneToMany references to NOV
List<ViolationTypeNOV> novRels = UnitOfWork.Context.ViolationTypeNOVs.Where(x => x.NOVId == nov.NOVId).Include("ViolationType").Include("NOV").ToList();
nov?.ViolationTypeNOVs?.Clear();
//foreach (ViolationTypeNOV o in novRels)
//{
// UnitOfWork.Context.ViolationTypeNOVs.Remove(o);
// o?.ViolationType?.ViolationTypeNOVs?.Remove(o);
// nov?.ViolationTypeNOVs?.Remove(o);
//}
UnitOfWork.Context.ViolationTypeNOVs.RemoveRange(novRels);
List<ViolationNOV> violationNOVs = UnitOfWork.Context.ViolationNOVs.Where(x => x.NOVId == nov.NOVId).Include("Violation").Include("NOV").ToList();
nov?.ViolationNOVs?.Clear();
UnitOfWork.Context.ViolationNOVs.RemoveRange(violationNOVs);
List<CaseNOV> caseNOVs = UnitOfWork.Context.CaseNOVs.Where(x => x.NOVId == nov.NOVId).Include("Case").Include("NOV").ToList();
nov?.CaseNOVs?.Clear();
UnitOfWork.Context.CaseNOVs.RemoveRange(caseNOVs);
UnitOfWork.Context.SaveChanges();
if (dbOperation != null)
dbOperation.Commit();
LogHandler.LogInfo(2521, "Deleted NOV " + nov.NOVNumber);
return true;
}
catch (Exception ex)
{
LogHandler.LogError(2523, "Commit Fail in NOV Delete", ex);
if (dbOperation != null)
dbOperation.Rollback();
throw ex;
}
}
This statement has fixed the problem: UnitOfWork.Context.ViolationTypeNOVs.RemoveRange(novRels); thanks a lot for everybody who tried to help me
I have a Entity Framework based database with a few entities/models/table. For e.g. Documents Model, I am want to track all changes to each record in that table, in a seperate table called DocumentChanges Model/Table.
Could you please guide me on how to enable/tell EF to track/audit all changes to the table in a separate table?, not just a date time stamp, but save the full record for every change in a separate table.
The library Audit.EntityFramework can help you to do what you want.
You'll need to implement your own DataProvider to store the data formatted as you wish.
For example:
void StartUp()
{
//Setup to use your own provider to store the data
Audit.Core.Configuration.Setup()
.UseCustomProvider(new YourDataProvider());
//Setup to audit EF operations only for the table Documents
//(Your DbContext must inherit from AuditDbContext)
Audit.EntityFramework.Configuration.Setup()
.ForAnyContext(x => x.IncludeEntityObjects())
.UseOptIn()
.Include<Documents>();
}
class YourDataProvider : AuditDataProvider
{
public override object InsertEvent(AuditEvent auditEvent)
{
//Get some enviroment info:
var userName = auditEvent.Environment.UserName
//Get the complete log for the EF operation:
var efEvent = auditEvent.GetEntityFrameworkEvent();
foreach(var entry in efEvent.Entries)
{
// each entry is a modified entity (updated, deleted or inserted)
if (entry.Action == "Update")
{
//You can access the column values
var value = entry.ColumnValues["ID"];
//...or the columns changes
var changes = entry.Changes.Select(ch => ch.ColumnName + ": " +
ch.OriginalValue + " -> " + ch.NewValue);
}
//... insert into DocumentChanges table
}
return id;
}
}
If I load entity object and then assign one of properties to the same value as it had before, does framework detect changes or it would set IsModified flag to true anyway ?
This is how generated code for field Name looks like:
OnNameChanging(value);
ReportPropertyChanging("Name");
_Name = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Name");
OnNameChanged();
I don't know which of those events set IsModified flag for that field and for the whole entity.
It looks like things are different now (EF6). I was researching this to see if I needed to use an if statement when setting property values to see if the "new value" is different. I tested with the following and the entity is not marked as modified:
var things = dbContext.Things.AsQueryable();
var thing = things.First();
string name = thing.Name;
thing.Name = name;
var entry = dbContext.Entry(thing);
var state = entry.State;
int count = dbContext.ChangeTracker.Entries().Count(e => e.State == EntityState.Modified);
var modified = entry.Property(x => x.Name).IsModified;
Your context only keeps track if your data got modified, not if it's different.
You can do a check like this:
private void CheckIfDifferent(DbEntityEntry entry)
{
if (entry.State != EntityState.Modified)
return;
if (entry.OriginalValues.PropertyNames.Any(propertyName => !entry.OriginalValues[propertyName].Equals(entry.CurrentValues[propertyName])))
return;
(this.dbContext as IObjectContextAdapter).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity).ChangeState(EntityState.Unchanged);
}
source:https://stackoverflow.com/a/13515869/1339087
i know how to do updates, inserts and deletes with the entityframework but in this case i don't know what to do.
In this case i have 3 tables: the table A the table B and the table AB which has 2 columns, one is the foreing key of the table A and one is the foreing key of the table B.
The entity framework shows only the tables A and B so how i can update only the content of the table AB?
I've tried to use the references in entity A and entity B but it gives me an exception saying that the entityset AB doesn't have the insert function and the delete function.
You try to make a
Public Virtual List<int> Ids
in your "A" and "B" Class to recover all the associations
For an insert, you would create a record for Table A, then add the Table B records to the item created that inserts into A. EF will handle the rest.
var tableA = new TableAtype { Description = "blah", etc.};
tableA.TableBtype.Add(new TableBtype { Property1 = "foo", Property2 = "bar"};
yourContext.AddToTableAtype(tableA);
yourContext.SaveChanges();
i'll be more specific using the code of my project as asked by TheGeekYouNeed
public void ModificaAbilitazioni(int IdGruppoAnagrafica, List<DefAbilitazioni> AbilitazioniList)
{
GruppiAnag gruppo = (from g in entities.GruppiAnags
where g.IdGruppoAnag == IdGruppoAnagrafica
select g).First();
List<DefAbilitazioni> tutteAbilitazioni = GetTutteAbilitazioni();
for (int i = 0; i < AbilitazioniList.Count; i++)
{
if (tutteAbilitazioni[i].GruppiAnags.Contains(gruppo))
{
tutteAbilitazioni[i].GruppiAnags.Remove(gruppo);
}
}
foreach (DefAbilitazioni abilitazione in AbilitazioniList)
{
for (int i = 0; i < tutteAbilitazioni.Count; i++)
{
if (tutteAbilitazioni[i].IdAbilitazione == abilitazione.IdAbilitazione)
{
tutteAbilitazioni[i].GruppiAnags.Add(gruppo);
}
}
}
entities.SaveChanges();
}
ok...here it is
this method should change the privilegies accounts.
First i recover the account using his id, than i recover all the privilegies and if in their reference they have the account recovered, then i remove it from the reference.
This way the account doesn't have any privilegies. Now in the privilegies that i've passed calling the method and in theri reference i put the account. (just a wipe and refill i'm just trying for now...)
i've also di the opposite, wiping the privilegies references in the account and refill them, but in both way won't work, in the first case it says that the third entity (AB) doesn't have the insert function
i've resolved the thing, the problem was that i was working with objects not attached to the db, i've tried with the attach like this
foreach (DefAbilitazioni abilitazione in abilitazioni)
{
entities.Attach(abilitazione);
gruppo.DefAbilitazionis.Add(abilitazione);
}
but it doesn't work it says that the entitykey is null, maybe if somebody gives me an example of using the attach i'll try to change my code that now is like this
public void ModificaAbilitazioni(int IdGruppoAnagrafica, List<DefAbilitazioni> AbilitazioniList)
{
GruppiAnag gruppo = (from g in entities.GruppiAnags
where g.IdGruppoAnag == IdGruppoAnagrafica
select g).First();
IEnumerable<int> idAbilitazioni = from id in AbilitazioniList
select id.IdAbilitazione;
List<DefAbilitazioni> abilitazioni = (from abilitazione in entities.DefAbilitazionis
where idAbilitazioni.Contains(abilitazione.IdAbilitazione)
select abilitazione).ToList();
gruppo.DefAbilitazionis.Clear();
foreach (DefAbilitazioni abilitazione in abilitazioni)
{
gruppo.DefAbilitazionis.Add(abilitazione);
}
entities.SaveChanges();
}
I have two tables Employee (n) and Store (1), which have n:1 relationship.
Employee has foreign key idStore which is primary key from Store.
Here is how I try to delete a row from Employee:
public void deleteEmployee(int idEmployee)
{
MyEntities pe = new MyEntities();
try
{
var firstQuery = from e in pe.Employees
where e.idEmployee == idEmployee
select e;
string findIdStore = firstQuery.First().StoreReference.EntityKey.EntityKeyValues[0].Value.ToString();
int idStore = Int32.Parse(findIdStore);
Store r = pe.Stores.First(c => c.idStore == idStore);
r.Employees.Remove(firstQuery.First());
pe.DeleteObject(firstQuery.First());
pe.SaveChanges();
}
catch (Exception ex)
{
return;
}
}
And still, I get error that the delete statement conflicted with the reference constraint.
The complete error is here:
The DELETE statement conflicted with the REFERENCE constraint
"FK_Bill_Employee". The conflict occurred in database
"myDatabase", table "dbo.Bill", column 'idEmployeeMember'.
The statement has been terminated.
Can't you just find and delete the employee??
public void deleteEmployee(int idEmployee)
{
using(MyEntities pe = new MyEntities())
{
var emmployeeToDelete = pe.Employees.FirstOrDefault(e => e.idEmployee == idEmployee);
if(employeeToDelete != null)
{
pe.DeleteObject(employeeToDelete);
pe.SaveChanges();
}
}
}
I don't think you need to do anything more than this, really.....
Next time when you load this particular store the employee belonged to, that employee will no longer be in the store's collection of employees - without doing any messy manual deletes or anything....