简体   繁体   中英

Proper Way to Update Properties of an Entity in Entity Framework 4.3 - Code First

What is the proper way to do an update when properties of an entity change? For example, I have an entity called Application. Application has a property List<TaskBases>. When running my app, Application has zero TaskBases. I just need to simply know how to save this list when a user adds a TaskBase to it.

The first line in the Save() method is new. I tried it because I found it while researching.

public void Save(Application application)
{
    // This line didn't work. See error below this code snippet.
    this.Database.Entry(application).Property(app => app.Tasks).IsModified = true;
    this.SaveChanges<Application>(application);
}

protected void SaveChanges<T>(T entity) where T : EntityBase
{
    this.Database.Entry<T>(entity).State = GetState(entity);
    this.Database.SaveChanges();
}

I get this error: "The property 'Tasks' on type 'Application' is not a primitive or complex property. The Property method can only be used with primitive or complex properties. Use the Reference or Collection method."

So then I tried using Reference and Collection, but I don't see anything in intellisense that would help me.

Note: When I first tried saving without having that first line in Save(), the item in the list of TaskBases didn't show up in the DB.

I have a feeling I'm making this harder than it needs to be. I have an entity, a user adds another entity to it, as part of a list, and I want that to save. What am I missing? How should this be done?

EDIT:

When I changed my Save() method to this, it worked:

public void Save(Application application)
{
    foreach (TaskBase taskBase in application.Tasks)
    {
        this.Database.Entry<TaskBase>(taskBase).State = GetState(taskBase);
    }

    this.SaveChanges<Application>(application);
}

Is that what has to be done? Is that the right way?

The normal method for performing updates goes something like this:

using(var context = new MyDbContext())
{
    var app = context.Applications.Single(a=>a.Id == theAppIdImInterestedIn); 
    app.Tasks.Add(new Task{ Name = "some other data" });
    context.SaveChanges();
}

If you want to separate this out a bit abstract your context away using a DI container to manage its lifecycle.

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