I have added a prop to my class and added a new DbSet
but when saving, it does not store my child objects.
My house class:
[Table("Houses")]
public class House
{
[Key]
public int ID { get; set; }
public List<Price> Prices { get; set; } // <-- new prop
}
my dbcontext has a Prices
prop now: public DbSet<Price> Prices { get; set; }
and I enabled migrations, added the migration and updated the database. So the prices table is created.
When I update a House
object, it does not insert anything in the Prices
table.
var h = new House(); // with prices etc filled
if (db.Houses.Any(hc => hc.Code.Equals(h.Code, StringComparison.InvariantCultureIgnoreCase)))
{
var original = db.Houses.First(k => k.Code.Equals(h.Code, StringComparison.InvariantCultureIgnoreCase));
h.ID = original.ID; // workaround for The property 'ID' is part of the object's key information and cannot be modified.
h.CountryId = original.CountryId;
db.Entry(original).CurrentValues.SetValues(h);
db.SaveChanges(); // does update House fields, but no prices
} else { // add new
db.Houses.Add(h);
db.SaveChanges();
}
I did add public virtual House House { get; set; }
to my Price
class. But I do not fill it, because when populating the house object, I do not know the ID in the db yet. Maybe that is causing it? I have also read https://stackoverflow.com/a/26572122/169714 and added this to my Price
class:
[ForeignKey("HouseId")]
public virtual House House { get; set; }
public int HouseId { get; set; }
but still no entries in the prices table. I am probably doing something wrong storing/updating the database.
edit current store method:
using (var db = new MyCommon.HouseContext())
{
var l = db.Countries.First(tmpC => tmpC.Code.Equals(h.Country.Code));
h.OperatorId = op.ID;
h.CountryId = l.ID;
h.Country = l;
var existingHouse = db.Houses.Where(p => p.Code.Equals(h.Code, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();
if (existingHouse != null)
{
// update
h.ID = existingHouse.ID; // workaround for The property 'ID' is part of the object's key information and cannot be modified.
h.CountryId = existingHouse.CountryId;
h.OperatorId = existingHouse.OperatorId;
db.Entry(existingHouse).CurrentValues.SetValues(h);
db.Entry(existingHouse).State = System.Data.Entity.EntityState.Modified;
//db.SaveChanges(); // moved to bottom for perf.
}
else
{
existingHouse = h;
db.Houses.Add(h); // insert
}
foreach (var ft in existingHouse.Prices)
{
var existingFt = existingHouse.Prices.SingleOrDefault(f => f.ID == ft.ID);
if (existingFt != null)
{
db.Entry(existingFt).CurrentValues.SetValues(ft);
db.Entry(existingFt).State = System.Data.Entity.EntityState.Modified;
}
else
{
existingHouse.Prices.Add(ft);
}
}
db.SaveChanges();
}