Manoz
Manoz

Reputation: 6587

EntityObject to DbContext

I am not sure in terms of exact technical specification for this problem to me but in simple words I am trying to create a wrapper/extension method around to save my entities.

So I added new Entity Data Model (.edmx) file to my project. That generates DbSet(s) like this-

 public partial class SUContextContainer : DbContext
    {
        public SUContextContainer()
            : base("name=SUContextContainer")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<Category> Categories { get; set; }
        public DbSet<Gallery> Galleries { get; set; }
        public DbSet<SuperUser> SuperUsers { get; set; }
        public DbSet<UserType> UserTypes { get; set; }
    }

Now here I am trying to wrap this into an extension method for database operations like (save, delete, update etc..)

I tried creating it as -

 public static void Save(this EntityObject objEntity)
        {
            try                                                         // Update Record
            {
                ((IObjectContextAdapter)Global.Context).ObjectContext.ObjectStateManager.ChangeObjectState(objEntity, EntityState.Modified);
                Global.Context.SaveChanges();
            }
            catch (OptimisticConcurrencyException)                      // Insert Record
            {
                ((IObjectContextAdapter)Global.Context).ObjectContext.ObjectStateManager.ChangeObjectState(objEntity, EntityState.Added);
                Global.Context.SaveChanges();
            }
        }

This method is attached to EntityObject types. Where .edmx code which it generates are of type DbContext.

So Whenever I try to save some entity with this helper method it never finds out.

 var galleryEntity = new Gallery {
       IsActive = true,
       CategoryId = model.CategoryId,
     };
  galleryEntity.Save(); // the save method is not found. 

I tried above method to change in -

 public static void Save(this DbSet objEntity)

But this also doesn't seem to take as extension method. What am I doing wrong.

Upvotes: 3

Views: 1524

Answers (2)

Erkan Demirel
Erkan Demirel

Reputation: 4382

So Whenever I try to save some entity with this helper method it never finds out.

It will not, because gallery is just a class and is not inherited from EntityObject.

I don't suggest adding inheritence or modifiying autogenerated classes.

Use power of partial classes:

You can create patial classess for your models with interface.

public partial class Gallery : IEntity
{
    //This is your class different than auto generated class by Ef.
}

Also you shouldn't use try catch for decision. That's why you should seperate update and create and make decision on upper level (without try catch).

So your extension methods should be like this.

public static int Update<T>(this T entity) where T : IEntity
{
    using(var dbContext=new SUContextContainer())
    {
      var entry = dbContext.Entry(entity);
      dbContext.Set<T>().Attach(entity);
      entry.State = EntityState.Modified;
      return dbContext.SaveChanges();
    }
}

public static int Create<T>(this T entity) where T : IEntity
{
    using(var dbContext=new SUContextContainer())
    {
      dbContext.Set<T>().Add(entity);
      return dbContext.SaveChanges();
    }
}

Upvotes: 2

Glen Thomas
Glen Thomas

Reputation: 10744

Your extension method will only apply to types that inherit from EntityObject. You will either need to make all of your entity classes inherit from this EntityObject class or create another extension method that applies to the correct type.

Typically when using these kind of persistence patterns you would create an entity base class

public class Entity
{
    public int Id { get; set; }
}

and each entity type inherits from it

public class Gallery : Entity
{
    public int Name { get; set; }
}

Then you can have common methods that you use across entity types:

public static void Save(this Entity entity);

Upvotes: 1

Related Questions