简体   繁体   中英

Child Entities Don't Update/Add

In my application, one entity relationship is shown in the below diagram.

在此处输入图片说明

It is as simple as below.

Qustion has TransQuestions and the question can fall in many subcategories

I have to add/update delete the DETACHED question throughout the life cycle of the application. Addition and deletion is simple. But for update i googled and got 3 below options.

1 to retrieve the old entity, replicate all the properties one by one and from updated entity to old one and then save the old entity again. I implemented this approach and its working fine but its bell for change management.

2 Attach the entity like DataSource.Questions.Attach(Entity); and then modify its state by DataSource.Entry(Entity).State = System.Data.EntityState.Modified; .

3 Use the SetValues method, example code is below.

        var oldData = DataSource.Questions.Find(Entity.QuestionID);
        if (oldData != null)
        {
            DataSource.Entry(oldData).CurrentValues.SetValues(Entity);
            DataSource.SaveChanges();
        }

I tested the 2nd approach and it worked for parent entity, then i also changed the sate of child entities and it worked fine too.

The problem is I have to update the object in many scenarios like the question is going to be attached with new subcategories or more TransQuestions are added to the question. In these scenarios we may have add subcategories operations too.

Below is the required scenario of 3 modifications

For any questions,

1 it is marked as ModifiedBy = 5,

2 TransQuestions is added for say French language (LanguageID = 'French')

3 Option2 in TransQuestions of already existing English (LanguageID = 'English)' is modified.

What should I do?

Thanks in advance.

If you should work with disconnected entities you can use GraphDiff .

using (var context = new TestDbContext())  
{
    //1. Load a Question from Db
    var question = context.Questions
                          .Include("TransQuestions")                        
                          .Where(/*some conditions*/)
                          .AsNoTracking() 
                          .FindFirstOrDefault();  
    //2. Do some changes with question and its childs
    .... 

    //3. Update Db values with changed question values
    context.UpdateGraph(question, 
                        map => map.OwnedCollection(p => p.TransQuestion));

    context.SaveChanges();
}

More informations

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM