jeudi 29 décembre 2016

Using Generic Repository Pattern With Deattached Entities

I am using generic repository pattern with deattached objects.I have different layers.In my web layer(where I make crud operations on entities) I have simple generic save method as shown in the below.

MyEntityService.Save(Entity)

In the service layer(where I have DbContext commit changes to db)

I removed some lines for brevity.

    private void SetMyEntityStates(IEntityCommon entity)
    {
        if (entity == null )
        {
            return;
        }

        var navProperties= entity.GetNavigationProperties;

        foreach (var navprop in navProperties)
        {

            if (typeof(IEntityCommon).IsAssignableFrom(p.PropertyType))
            {
                var val = p.GetValue(entity) as IEntityCommon;
                if (val != null)
                {
                    var entry = Context.Entry(val);
                    if (entry.State == EntityState.Detached || entry.State == EntityState.Unchanged)
                    {
                        entry.State = val.IsNew() ? EntityState.Added : EntityState.Modified;
                        SetMyEntityStates(val);
                    }
                }
            }
        }
    }

Because I don't know which property or navigation property is modified in the web layer I change state of all of navigation properties even nav properties of nav properties recursively to modified/added.

Because all of my entities have at least one navigation property I almost flag all entities in my Context as modified.

Must I do modify every nav prop recursively as I do ?

Consider the example below,If I change a customer's home price ,must I change entity state for both home and price or home is enough?

 public class Customer
 {
   virtual ICollection<Home> {get; set;}
 } 

 public class Home
 {
  virtual ICollection<Price> {get; set;}
 }

 public class Price
 {
  PriceType {get;set;}/1 2 3 Euro Gbp Dollar
  Value {get;set;}
 }

For each entity state that I change to modified EF creates a update sql ? If there any other way to accomplish my task ?

Thanks in advance





Aucun commentaire:

Enregistrer un commentaire