Creating Object in EF which is null after saveChanges in DB - c#

after i set the AuditReport on my Audit and save it, (in Debugger it is filled with a Proxy) there is still no Entry in the Database and I have no Idea why. Here are the relevant classes:
public class AuditReport
{
[Key]
[ForeignKey("Audit")]
[Column("AuditReport_ID")]
public int ID { get; set; }
[Required]
public virtual Audit Audit { get; set; }
}
public class Audit
{
[Key]
public int GeneratedID { get; set; }
[Index("Audit_ID", IsUnique = true)]
public int Audit_ID { get; set; }
public virtual AuditReport AuditReport { get; set; }
}
And the method in that the new AuditReport is Created
public async override Task SaveChangesAsync()
{
using (var dbAccess = new DatabaseAccess())
{
var foundAudit = dbAccess.Audits.Include("AuditReport").Include("AuditReport.Stellungnahmen").SingleOrDefault(_ => _.Audit_ID == Audit.Audit_ID);
if (foundAudit != null)
{
if (foundAudit.AuditReport == null)
{
foundAudit.AuditReport = dbAccess.AuditReports.Create();
foundAudit.AuditReport.Audit = foundAudit;
}
else
foundAudit.AuditReport.Stellungnahmen.ToList().ForEach(_ => dbAccess.Entry(_).State = EntityState.Deleted);
foreach (var item in Stellungnahmen.Where(_ => _.IsChecked == true))
foundAudit.AuditReport.Stellungnahmen.Add(dbAccess.Stellungnahmen.SingleOrDefault(_ => _.KeyWord == item.KeyWord));
}
await dbAccess.SaveChangesAsync();
}
}
As i already said, I've already debugged it and everything looks fine.

Try to remove [Key] on ID since you already have [ForeignKey] atrribute.

Related

EF Core table first not saving entities in the database

I'm new to EF (table first) and I don't know why these related entities are not saving at all to my database.
These are the related entities, UserProfile has a set of Carts
public partial class UserProfile
{
public UserProfile()
{
Cart = new HashSet<Cart>();
Naquestions = new HashSet<Naquestions>();
}
public int Id { get; set; }
public string BotUserId { get; set; }
public int? PrestashopId { get; set; }
public bool Validated { get; set; }
public int Permission { get; set; }
public DateTime CreationDate { get; set; }
public ICollection<Cart> Cart { get; set; }
public ICollection<Naquestions> Naquestions { get; set; }
}
Cart has a set of OrderLines
public partial class Cart
{
public Cart()
{
OrderLine = new HashSet<OrderLine>();
OrderRequest = new HashSet<OrderRequest>();
}
public int Id { get; set; }
public int UserId { get; set; }
public bool Active { get; set; }
public UserProfile User { get; set; }
public ICollection<OrderLine> OrderLine { get; set; }
public ICollection<OrderRequest> OrderRequest { get; set; }
}
And when I try to add them:
public async Task AddOrderLineToUser(string botId, OrderLine orderLine)
{
using (var context = ServiceProvider.CreateScope())
{
var db = context.ServiceProvider.GetRequiredService<GretaDBContext>();
var user = await UserController.GetUserByBotIdAsync(botId);
var latestCart = user.Cart.OrderByDescending(c => c.Id).FirstOrDefault();
if (latestCart != null && latestCart.Active)
{
latestCart.OrderLine.Add(orderLine);
}
else
{
var newCart = new Cart()
{
Active = true,
};
newCart.OrderLine.Add(orderLine);
user.Cart.Add(newCart);
}
await db.SaveChangesAsync();
}
}
Nothing is saving to the database once db.SaveChangesAsync() is called.
As #Caius Jard said in the comments it seems that user comes from another context. Try
if (latestCart != null && latestCart.Active)
{
orderLine.CartId = latestCart.Id;
db.OrderLines // I assume it is name of your orderlines DbSet
.Add(orderLine);
}
else
{
var newCart = new Cart()
{
Active = true,
UserId = user.Id,
};
newCart.OrderLine.Add(orderLine);
db.Carts // also assuming name of DbSet
.Add(newCart);
}
Also you can take a look at Attach method.
But I would say that in general you are doing something not good. Usually creating new scope is not needed, and db context should be injected in corresponding class via ctor. If you still need to create new scope it would make sense to resolve UserController also. Also is UserController an ASP controller?

How to update data in a related table in EF?

There are two such models:
public class Form
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid FormId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public List<BlockWorkingForm> BlocksWorkingForm { get; set; }
}
public class BlockWorkingForm
{
[Key]
[Column(Order = 1)]
public string Header { get; set; }
[Key]
[Column(Order = 2)]
public Guid FormId { get; set; }
public Form Form { get; set; }
public string Field { get; set; }
public bool MandatoryQuestion { get; set; }
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (!(obj is BlockWorkingForm m))
{
return false;
}
return m.Header == this.Header
&& m.Field == this.Field
&& m.Type == this.Type
&& m.MandatoryQuestion == this.MandatoryQuestion;
}
}
And there is such a method for updating the model.
public void UpdateForm(Form form)
{
EditorFormContext context = new EditorFormContext();
var formDb = this.context.Forms.Include(x => x.BlocksWorkingForm).Single(x => x.FormId == form.FormId);
this.context.Entry(formDb).CurrentValues.SetValues(form);
foreach (var itemForm in form.BlocksWorkingForm)
{
if (itemForm.FormId == Guid.Empty)
{
itemForm.FormId = formDb.FormId;
this.context.BlocksWorkingForm.Add(itemForm);
}
foreach (var itemFormDb in formDb.BlocksWorkingForm)
{
if (itemForm.Header != itemFormDb.Header)
{
continue;
}
if (!itemForm.Equals(itemFormDb))
{
this.context.Entry(itemFormDb)
.CurrentValues.SetValues(itemForm);
}
}
}
this.context.SaveChanges()
}
Now it only allows updating the Title and Description fields in the Database in the Form, as well as adding new blocks (BlockWorkingForm) for the form. But it is still necessary to implement the removal of these blocks.
To remove blocks, I need to compare what is in the database and what came in the Update method, but how can this be done?
This this.context.Entry(formDb).CurrentValues.SetValues(form); is where your properties (Title and Description) are set in the DB object. But The list of BlocksWorkingForm is not set (or not set properly).
If you add the BlocksWorkingForms in the form yourself, the insert should work properly.
This should work.
public void UpdateForm(Form form)
{
EditorFormContext context = new EditorFormContext();
var formDb = this.context.Forms.Include(x => x.BlocksWorkingForm).Single(x => x.FormId == form.FormId);
this.context.Entry(formDb).CurrentValues.SetValues(form);
formDb.BlocksWorkingForm = form.BlocksWorkingForm;
this.context.SaveChanges()
}

Entity Framework many to many relationship add/update

I have two entities, and when I update or add only one all is ok
db.Entry(user1).State = EntityState.Modified;
foreach (var userAudio in user1.Audios)
{
db.Audios.AddOrUpdate(userAudio);
}
db.Users.AddOrUpdate(user1);
db.SaveChanges();
But if I try add/update few entities:
db.Entry(user1).State = EntityState.Modified;
foreach (var userAudio in user1.Audios)
{
db.Audios.AddOrUpdate(userAudio);
}
db.Users.AddOrUpdate(user1);
db.Entry(user2).State = EntityState.Modified;
foreach (var userAudio in user2.Audios)
{
db.Audios.AddOrUpdate(userAudio);
}
db.Users.AddOrUpdate(user2);
db.SaveChanges();
It is throwing exception:
Attaching an entity of type 'EfTest.Entities.Audio' failed because
another entity of the same type already has the same primary key
value...
Maybe it is because I have same audios in user1 and user2, and EF can't insert them...Anyone have ideas how to get round this? thanks!
Entities
namespace EfTest.Entities
{
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public List<Audio> Audios { get; set; }
}
public class Audio
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string Artist { get; set; }
public string Title { get; set; }
public List<User> Users { get; set; }
}
}
Unfortunately I see only one way to solve this. It is adding entities independently and then adding relations:
var userAudios = new List<Audio>();
// Key userId
// Value list of audiosIds
var userAudiosRelations = new List<Relation>();
foreach (var user in users)
{
foreach (var audio in user.Audios)
{
if (!userAudios.Any(x => x.Id == audio.Id))
{
userAudios.Add(audio);
}
userAudiosRelations.Add(new Relation
{
User_Id = user.Id,
Audio_Id = audio.Id
});
}
user.Audios = null;
db.Users.AddOrUpdate(user);
}
foreach (var audio in userAudios)
{
db.Audios.AddOrUpdate(audio);
}
db.SaveChanges();
var existingRelations = db.Database.SqlQuery<Relation>("SELECT * FROM dbo.UserAudios").ToList();
var relationsToAdd =
userAudiosRelations.Where(
x => existingRelations.All(y => x.User_Id != y.User_Id || x.Audio_Id != y.Audio_Id)).ToList();
foreach (var relation in relationsToAdd)
{
db.Database.ExecuteSqlCommand("INSERT INTO dbo.UserAudios (User_Id, Audio_Id) VALUES (#p0, #p1)",
relation.User_Id, relation.Audio_Id);
}
Where relation model:
public class Relation
{
public int User_Id { get; set; }
public int Audio_Id { get; set; }
}

Entity Framework sets property to null when saving

I got a weird issue I can't explain.
I'm working with EF here. Got a method that copies some values from a wrapper object into the object I already have in the database. The object in the database has to be updated with the values in the wrapper object.
Here's the code:
private void UpdateAudit(AuditWrapper audit, DatabaseAccess dbAccess)
{
var foundAudit = dbAccess.Audits.Include("Auditors").SingleOrDefault(_ => _.Audit_ID == audit.Audit_ID);
if(foundAudit != null)
{
foundAudit.Auditorennamen = audit.Auditorennamen;
foundAudit.AuditTarget = audit.AuditTarget;
foundAudit.Scopes = audit.Scopes;
foundAudit.Location = audit.Location;
foundAudit.Address = audit.Address;
foundAudit.Auditors.Clear();
foreach (var item in audit.Auditors)
{
var usr = dbAccess.Users.SingleOrDefault(_ => _.Username == item.Username);
if (usr != null)
{
var uta = dbAccess.User_To_Audit.Create();
uta.Function = item.Function;
uta.User = usr;
uta.Audit_GeneratedID = foundAudit.GeneratedID;
uta.Audit = foundAudit;
foundAudit.Auditors.Add(uta);
}
}
}
dbAccess.SaveChanges();
}
In the User_To_Audit object the Audit is set to null, even though it wasn't null when I selected it from the database.
No idea why it is set to null when I use db.SaveChanges().
Well, I don't know if the property is really null, but I can tell it saves null into the database in the foreign key column.
I've already tried to only set the GeneratedID or only set the Audit or set none of them. Every time the same effect.
[ForeignKey("Audit")]
public int Audit_GeneratedID { get; set; }
public virtual Audit Audit { get; set; }
Please help
update:
Audit has a List<User_To_Audit>.
User_To_Audit has a reference to the Audit it belongs to.
public class Audit
{
[Key]
public int GeneratedID { get; set; }
[Index("Audit_ID", IsUnique = true)]
public int Audit_ID { get; set; }
.
.
.
public virtual List<User_To_Audit> Auditors { get; set; }
}
public class User_To_Audit
{
[Key]
public int ID { get; set; }
public virtual User User { get; set; }
[ForeignKey("Audit")]
public int Audit_GeneratedID { get; set; }
public virtual Audit Audit { get; set; }
public virtual AuditorFunction Function { get; set; }
}

Entity Framework adding too many records

EDIT: See the bottom of this question for the working code.
I have two tables, Patients and Drugs, that I am updating with a data feed. I get a current list of patients, then iterate through and update or insert records as appropriate. This works without issue.
The trouble comes when I iterate through that patient's current medications. I end up getting multiple copies of the original patient. Drug records are transferred as expected (the records themselves don't change so new records are inserted and existing records ignored). I end up with the original patient record (inserted from UpdatePatients() below) and then one additional patient record for each medication record. Each medication record ends up with a distinct PatientId.
Class definitions:
public class Patient
{
public int PatientId { get; set; }
[Required]
public int FacilityNumber { get; set; }
[Required]
public int PatNo { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Age { get; set; }
[Required]
public string Gender { get; set; }
[Required]
public DateTime VentStart { get; set; }
[Required]
public DateTime VentEnd { get; set; }
[Required]
public DateTime AdmitDate { get; set; }
public DateTime? DischargeDate { get; set; }
}
public class Drug
{
public int DrugId { get; set; }
[Required]
public int DrugDDI { get; set; }
[Required]
public int OrderId { get; set; }
[Required]
public string DrugName { get; set; }
[Required]
public DateTime DispenseDate { get; set; }
[Required]
public double UnitsDispensed { get; set; }
[ForeignKey("Patient")]
public int PatientId { get; set; }
public virtual Patient Patient { get; set; }
}
Offending code:
private static void UpdatePatients()
{
var Patients = DB2Patient.GetPatients();
foreach (Patient p in Patients)
{
using (var PatientContext = new VAEContext())
{
var ExistingPatientRecord = PatientContext.Patients.FirstOrDefault(
ep => ep.PatNo == p.PatNo
);
if (ExistingPatientRecord != null)
{
ExistingPatientRecord.VentEnd = p.VentEnd;
ExistingPatientRecord.DischargeDate = p.DischargeDate;
PatientContext.SaveChanges();
}
else
{
PatientContext.Patients.Add(p);
PatientContext.SaveChanges();
}
}
UpdateDrugs(p);
}
}
private static void UpdateDrugs(Patient p)
{
var Drugs = DB2Drug.GetDrugs(p.PatNo);
foreach (Drug d in Drugs)
{
using (var DrugContext = new VAEContext())
{
var ExistingDrugRecord = DrugContext.Drugs.FirstOrDefault(
ed => ed.DrugDDI == d.DrugDDI &&
ed.DispenseDate == d.DispenseDate &&
ed.OrderId == d.OrderId
);
if (ExistingDrugRecord == null)
{
d.Patient = p;
DrugContext.Drugs.Add(d);
DrugContext.SaveChanges();
}
}
}
}
EDIT: Working code:
private static void UpdatePatients()
{
var Patients = DB2Patient.GetPatients();
using (var db = new VAEContext())
{
foreach (Patient p in Patients)
{
var ExistingPatientRecord = db.Patients.FirstOrDefault(
ep => ep.PatNo == p.PatNo
);
if (ExistingPatientRecord != null)
{
ExistingPatientRecord.VentEnd = p.VentEnd;
ExistingPatientRecord.DischargeDate = p.DischargeDate;
}
else
{
db.Patients.Add(p);
}
UpdateDrugs(p, db);
}
db.SaveChanges();
}
}
private static void UpdateDrugs(Patient p, VAEContext ctx)
{
var Drugs = DB2Drug.GetDrugs(p.PatNo);
foreach (Drug d in Drugs)
{
var ExistingDrugRecord = ctx.Drugs.FirstOrDefault(
ed => ed.DrugDDI == d.DrugDDI &&
ed.DispenseDate == d.DispenseDate &&
ed.OrderId == d.OrderId
);
if (ExistingDrugRecord == null)
{
d.Patient = p;
ctx.Drugs.Add(d);
}
}
}
Why new context every time something needs to be inserted? Both methods UpdatePatients and UpdateDrugs are private, you can use the same context for all linked operations and I'm sure you won't get the duplicates:
private static void UpdateDrugs(Patient p, VAEContext context)
...
Also there's probably no need to save on every drug, doing so likely decreases performance and doesn't do much in terms of data integrity. Consider saving the context changes once per linked updates (say after UpdateDrugs is called in UpdatePatients)
Other than that you can check out the ObjectContext.Attach and related methods on how to link the Patient object to your newly created Drugs context instance
http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attach.aspx

Categories