I have a parent object which has the collection of the child objects. I want to save this data into the DB using EF Code First. For some strange reason the parent object gets saved but the child objects not.
Here's my code:
class Person
{
public Person()
{
Operations = new ICollection<Operation> ();
}
public int Id { get; set; }
public virtual ICollection<Operation> Operations { get; set; }
}
public class Operation
{
public int Id { get; set; }
public string Data { get; set; }
public int PersonId { get; set; }
public virtual Person Person{ get; set; }
}
Here's thee DAL UpdateMethod:
public bool UpdatePerson entity)
{
//_context.Set<Person>().AddOrUpdate(entity);
var entityInDb = _context.Persons.Find(entity.Id);
_context.Entry(entityInDb).CurrentValues.SetValues(entity);
_context.Entry(entityInDb).State = EntityState.Modified;
return _context.SaveChanges() > 0;
}
And here's the BLL:
//Create a new person if it does not exist. If exists, add only the Operations:
//check if such the person exists in the DB
var person = Repository.Filter(p=>p.Id == Id)
.AsNoTracking().FirstOrDefault();
//if not, create a new record
if(person == null)
{
personNew = new Person{
...
};
bool res = Repository.Insert(personNew );
if (res)
{
//find newly created person
person = Repository.Filter(p => p.Id == ...)
.AsNoTracking().FirstOrDefault();
}
}
//Add Operations to the Person entity and Save them:
var op = obj.ToOperationModel();
op.PersonId = person.Id;
person.Operations.Add(op);
var res2 = Repository.Update(person);
There is no error, the parent object (Person) gets created, res2 returns true, but no Operation is added into the DB
Modify the update method like this;
public bool UpdatePerson entity)
{
//_context.Set<Person>().AddOrUpdate(entity);
var entityInDb = _context.Persons.Include(x => x.Operations).FirstOrDefault(x => x.Id == entity.Id);//Add Include for navigation property
_context.Entry(entityInDb).CurrentValues.SetValues(entity);
_context.Entry(entityInDb).State = EntityState.Modified;
_context.Entry(entityInDb).Property(x => x.Operations).IsModified = true; // Add this line
return _context.SaveChanges() > 0;
}
To establish relationship between the entities, you can use DataAnnotations
attributes or Fluent Api. To associate relationships by using DataAnnotations
, modify the Operation
and Person
entities like this;
public class Operation
{
public int Id { get; set; }
public string Data { get; set; }
[ForeignKey("Person")] // Add ForeignKey attribute
public int PersonId { get; set; }
public virtual Person Person{ get; set; }
}
public class Person
{
public Person()
{
Operations = new ICollection<Operation> ();
}
[Key] // Add key attribute
public int Id { get; set; }
public virtual ICollection<Operation> Operations { get; set; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.