简体   繁体   中英

update entity and related entities

the scenario is:

class Foo {
    [Key]
    public int Id { get; set; }
    public List<Bar> Bars { get; set; }
}

class Bar {
     [Key]
     public int Id { get; set; }
     public string Name { get; set; }
}

I must implement a simple crud ops like this:

public void InsertOrUpdateFoo(Foo foo) {

    var db = new MyContext();

    //here some pseudocode
    if (foo exists) {

        d.Foos.Add(foo);

    } else {

        //here which is the best solution?
        //a good tradeoff between performance and code semplicity

        //case 1: delete first and add
        db.Foos.Remove(oldFoo);
        db.Add(foo);
        db.SaveChanges();

        //case 2: there is some functionality that allows you to update the entity like:
        db.Modify(oldEntity, newEntity);

    }

    db.Dispose();
}

In update scenario which seems to be the best choice?

  1. Delete and Add
  2. Manage manually the update (foreach subentities)
  3. Some other techniques??

Based on the idea in http://forums.asp.net/t/1889944.aspx , you could check to see if the ID property of the entity is a default value, such as 0 for an int. If so, it's new and should be added. If not, then update it.

This can be indicated to the context by its EntityState , once the entity is attached to the context. You can obtain access to this via the DbEntityEntry of the entity, through the context's Entry<T>() method.

You'll also want to use the using statement when you create the context, which will manage the scope of the context and automatically call Dispose on it when the block ends.

It's better to split it up into the part that actually saves the changes as an insert or update (a repository method, most likely, but will use it stand-alone here for simplicity) and the code that manipulates the entity.

Definition of the method (based on your code):

public void InsertOrUpdateFoo(DbContext db, Foo foo) {        
    if (foo.ID == 0) { // assuming Foo's unique identifier is named ID
        db.Entry(entity).State = EntityState.Added;
    } else {
        db.Entry(entity).State = EntityState.Modified;
    }
    db.SaveChanges();
}

Usage:

// for when you're creating new entities
var newFoo = new Foo();
newFoo.Name = "A Name";
using(var context = new MyContext())
{
    context.Add(newFoo);
    InsertOrUpdate(context. newFoo);
}

// ...
// for when you're using existing entities
// you have an ID from somewhere in variable "id"
using (var context = new MyContext())
{
    var existingFoo = context.Find(id);
    if (existingFoo != null)
    {
        existingFoo.Name = "ChangedTheName";
        InsertOrUpdate(context, existingFoo);
    }
}

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