Index: /branches/OaaS/HeuristicLab.Services.Optimization.Billing/BillingEngine/BillingEngine.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Optimization.Billing/BillingEngine/BillingEngine.cs	(revision 9644)
+++ /branches/OaaS/HeuristicLab.Services.Optimization.Billing/BillingEngine/BillingEngine.cs	(revision 9645)
@@ -89,5 +89,5 @@
               usageCharges.Invoice = invoice;
               usageCharges.Product = billingService.GetProductByName("Oaas Usage Charges").First();
-              usageCharges.ProductPrice = -999.99;
+              usageCharges.ProductPrice = 999.99;
               usageCharges.Quantity = 1;
               invoice.InvoiceLines.Add(usageCharges);
@@ -102,4 +102,5 @@
               UpdateBillingState(order);
               billingService.UpdateOrder(order);
+              billingService.SaveInvoice(invoice);
             }
           }
@@ -120,4 +121,5 @@
       }
 
+      order.LastBillableDay = currentDate;
       DateTime nextBillingDay = CalculateNextBillingDate(order);
 
@@ -130,4 +132,6 @@
         order.NextBillableDay = nextBillingDay;
       }
+
+      order.EntityState = State.Modified;
     }
 
Index: /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Business/BillingService.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Business/BillingService.cs	(revision 9644)
+++ /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Business/BillingService.cs	(revision 9645)
@@ -42,5 +42,5 @@
       //TODO: Authentication
       //TODO: Enable Transaction
-      BillingDao.AddOrder(order);
+      BillingDao.InsertOrUpdateOrder(order);
     }
 
@@ -59,5 +59,7 @@
 
     public void UpdateOrder(Order order) {
-      throw new System.NotImplementedException();
+      //TODO: Authentication
+      //TODO: Enable Transaction
+      BillingDao.InsertOrUpdateOrder(order);
     }
 
@@ -75,5 +77,5 @@
       //TODO: Authentication
       //TODO: Enable Transaction
-      BillingDao.AddUser(user);
+      BillingDao.InsertOrUpdateUser(user);
     }
 
@@ -104,4 +106,10 @@
     }
 
+    public void SaveInvoice(Invoice invoice) {
+      //TODO: Authentication
+      //TODO: Enable Transaction
+      BillingDao.InsertOrUpdateInvoice(invoice);
+    }
+
     #endregion
   }
Index: /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Business/MockupBillingService.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Business/MockupBillingService.cs	(revision 9644)
+++ /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Business/MockupBillingService.cs	(revision 9645)
@@ -134,4 +134,8 @@
     }
 
+    public void SaveInvoice(Model.Invoice invoice) {
+      throw new NotImplementedException();
+    }
+
     #endregion
   }
Index: /branches/OaaS/HeuristicLab.Services.Optimization.Billing/DataAccess/BillingContext.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Optimization.Billing/DataAccess/BillingContext.cs	(revision 9644)
+++ /branches/OaaS/HeuristicLab.Services.Optimization.Billing/DataAccess/BillingContext.cs	(revision 9645)
@@ -2,6 +2,8 @@
 using System.Collections.Generic;
 using System.Data.Entity;
+using System.Data.Entity.Infrastructure;
 using System.Data.Entity.ModelConfiguration;
 using System.Data.Entity.ModelConfiguration.Conventions;
+using HeuristicLab.Services.Optimization.Billing.Interfaces;
 using HeuristicLab.Services.Optimization.Billing.Model;
 
@@ -28,4 +30,15 @@
     public BillingContext(string connectionString)
       : base(connectionString) {
+
+      Database.SetInitializer(new HeuristicLab.Services.Optimization.Billing.DataAccess.BillingContext.BillingContextInitiliazer());
+
+      // Hook up event to mark existing entities as Unchanged
+      ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += (sender, args) => {
+        var entity = args.Entity as IObjectWithState;
+        if (entity != null) {
+          entity.EntityState = State.Unchanged;
+        }
+      };
+
       this.Configuration.LazyLoadingEnabled = false;
       this.Configuration.ProxyCreationEnabled = false;
@@ -33,4 +46,7 @@
 
     protected override void OnModelCreating(DbModelBuilder modelBuilder) {
+      modelBuilder.Configurations.Add(new ContactInformationConfiguration());
+      modelBuilder.Configurations.Add(new PaymentInformationConfiguration());
+      modelBuilder.Configurations.Add(new ProductConfiguration());
       modelBuilder.Configurations.Add(new OrderConfiguration());
       modelBuilder.Configurations.Add(new OrderLineConfiguration());
@@ -47,6 +63,25 @@
     #region EntityTypeConfigurations
 
+    private class ContactInformationConfiguration : EntityTypeConfiguration<ContactInformation> {
+      internal ContactInformationConfiguration() {
+        this.Ignore(ci => ci.EntityState);
+      }
+    }
+
+    private class PaymentInformationConfiguration : EntityTypeConfiguration<PaymentInformation> {
+      internal PaymentInformationConfiguration() {
+        this.Ignore(pi => pi.EntityState);
+      }
+    }
+
+    private class ProductConfiguration : EntityTypeConfiguration<Product> {
+      internal ProductConfiguration() {
+        this.Ignore(p => p.EntityState);
+      }
+    }
+
     private class OrderConfiguration : EntityTypeConfiguration<Order> {
       internal OrderConfiguration() {
+        this.Ignore(o => o.EntityState);
         this.HasRequired(o => o.User).WithMany().HasForeignKey(o => o.UserId);
         // TODO: OrderState?
@@ -56,4 +91,5 @@
     private class OrderLineConfiguration : EntityTypeConfiguration<OrderLine> {
       internal OrderLineConfiguration() {
+        this.Ignore(ol => ol.EntityState);
         this.HasRequired(ol => ol.Order).WithMany(o => o.OrderLines).HasForeignKey(ol => ol.OrderId).WillCascadeOnDelete(true);
         this.HasRequired(ol => ol.Product).WithMany().HasForeignKey(ol => ol.ProductId);
@@ -63,4 +99,5 @@
     private class InvoiceConfiguration : EntityTypeConfiguration<Invoice> {
       internal InvoiceConfiguration() {
+        this.Ignore(i => i.EntityState);
         this.HasRequired(i => i.User).WithMany().HasForeignKey(i => i.UserId);
         this.HasRequired(i => i.Order).WithMany(o => o.Invoices).HasForeignKey(i => i.OrderId);
@@ -70,4 +107,5 @@
     private class InvoiceLineConfiguration : EntityTypeConfiguration<InvoiceLine> {
       internal InvoiceLineConfiguration() {
+        this.Ignore(i => i.EntityState);
         this.HasRequired(il => il.Invoice).WithMany(i => i.InvoiceLines).HasForeignKey(il => il.InvoiceId).WillCascadeOnDelete(true);
         this.HasRequired(il => il.Product).WithMany().HasForeignKey(il => il.ProductId);
@@ -77,4 +115,5 @@
     private class UsageRecordConfiguration : EntityTypeConfiguration<UsageRecord> {
       internal UsageRecordConfiguration() {
+        this.Ignore(ur => ur.EntityState);
         this.HasRequired(ur => ur.User).WithMany().HasForeignKey(ur => ur.UserId);
         this.HasRequired(ur => ur.Product).WithMany().HasForeignKey(ur => ur.ProductId);
@@ -84,4 +123,5 @@
     private class UserConfiguration : EntityTypeConfiguration<User> {
       internal UserConfiguration() {
+        this.Ignore(u => u.EntityState);
         this.HasMany(u => u.PaymentInformation).WithRequired(pi => pi.User).HasForeignKey(pi => pi.UserId);
         this.HasRequired(u => u.ContactInformation).WithMany().HasForeignKey(u => u.ContactInformationId);
@@ -166,4 +206,5 @@
           BillingPeriod = BillingPeriod.Monthly,
         };
+
         OrderLine ol1 = new OrderLine() {
           Order = o1,
@@ -172,4 +213,5 @@
           Quantity = 1
         };
+
         o1 = context.Orders.Add(o1);
         ol1 = context.OrderLines.Add(ol1);
Index: /branches/OaaS/HeuristicLab.Services.Optimization.Billing/DataAccess/BillingDao.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Optimization.Billing/DataAccess/BillingDao.cs	(revision 9644)
+++ /branches/OaaS/HeuristicLab.Services.Optimization.Billing/DataAccess/BillingDao.cs	(revision 9645)
@@ -2,8 +2,10 @@
 using System;
 using System.Collections.Generic;
+using System.Data;
 using System.Data.Entity;
 using System.Linq;
 using System.Linq.Expressions;
 using HeuristicLab.Services.Optimization.Billing.Model;
+using HeuristicLab.Services.Optimization.Billing.Utils;
 namespace HeuristicLab.Services.Optimization.Billing.DataAccess {
   public class BillingDao {
@@ -16,36 +18,4 @@
     }
 
-    private delegate T ExecuteWithContextDelegate<T>(BillingContext context);
-    private delegate void ExecuteWithContextDelegate(BillingContext context);
-
-    private void ExecuteWithContext(ExecuteWithContextDelegate call) {
-      BillingContext context = null;
-      try {
-        using (context = CreateContext()) {
-          call(context);
-        }
-      }
-      finally {
-        if (context.Database.Connection.State == System.Data.ConnectionState.Open) {
-          context.Database.Connection.Close();
-        }
-      }
-    }
-
-    private T ExecuteWithContext<T>(ExecuteWithContextDelegate<T> call) {
-      BillingContext context = null;
-      try {
-        using (context = CreateContext()) {
-          T result = call(context);
-          return result;
-        }
-      }
-      finally {
-        if (context.Database.Connection.State == System.Data.ConnectionState.Open) {
-          context.Database.Connection.Close();
-        }
-      }
-    }
-
     #endregion
 
@@ -53,7 +23,7 @@
 
     public Product FindProductById(long id) {
-      return ExecuteWithContext<Product>((context) => {
+      using (var context = CreateContext()) {
         return context.Products.FirstOrDefault(prod => prod.ProductId == id);
-      });
+      }
     }
 
@@ -72,34 +42,26 @@
     }
 
-    public void AddProduct(Product entity) {
-      ExecuteWithContext((context) => {
-        context.Products.Add(entity);
+    public void InsertOrUpdateProduct(Product entity) {
+      using (var context = CreateContext()) {
+        throw new NotImplementedException();
+      }
+    }
+
+    void DeleteProduct(Product entity) {
+      using (var context = CreateContext()) {
+        throw new NotImplementedException();
+      }
+    }
+
+    #endregion
+
+    #region Order Methods
+
+    public void InsertOrUpdateOrder(Order entity) {
+      using (var context = CreateContext()) {
+        context.Orders.Add(entity);
+        context.ApplyStateChanges();
         context.SaveChanges();
-      });
-    }
-
-    public void UpdateProduct(Product entity) {
-      ExecuteWithContext((context) => {
-        context.Products.Attach(entity);
-        context.Entry(entity).State = System.Data.EntityState.Modified;
-        context.SaveChanges();
-      });
-    }
-
-    void DeleteProduct(Product entity) {
-      ExecuteWithContext((context) => {
-        context.Products.Remove(entity);
-      });
-    }
-
-    #endregion
-
-    #region Order Methods
-
-    public void AddOrder(Order order) {
-      ExecuteWithContext((context) => {
-        context.Orders.Add(order);
-        context.SaveChanges();
-      });
+      }
     }
 
@@ -122,7 +84,7 @@
 
     public OrderLine FindOrderLineById(long id) {
-      return ExecuteWithContext<OrderLine>((context) => {
+      using (var context = CreateContext()) {
         return context.OrderLines.FirstOrDefault(ol => ol.OrderLineId == id);
-      });
+      }
     }
 
@@ -141,23 +103,14 @@
     }
 
-    public void AddOrderLine(OrderLine entity) {
-      ExecuteWithContext((context) => {
-        context.OrderLines.Add(entity);
-        context.SaveChanges();
-      });
-    }
-
-    public void UpdateOrderLine(OrderLine entity) {
-      ExecuteWithContext((context) => {
-        context.OrderLines.Attach(entity);
-        context.Entry(entity).State = System.Data.EntityState.Modified;
-        context.SaveChanges();
-      });
+    public void InsertOrUpdateOrderLine(OrderLine entity) {
+      using (var context = CreateContext()) {
+        throw new NotImplementedException();
+      }
     }
 
     void DeleteOrderLine(OrderLine entity) {
-      ExecuteWithContext((context) => {
-        context.OrderLines.Remove(entity);
-      });
+      using (var context = CreateContext()) {
+        throw new NotImplementedException();
+      }
     }
 
@@ -167,7 +120,7 @@
 
     public User FindUserById(long id) {
-      return ExecuteWithContext<User>((context) => {
+      using (var context = CreateContext()) {
         return context.Users.FirstOrDefault(user => user.UserId == id);
-      });
+      }
     }
 
@@ -186,23 +139,14 @@
     }
 
-    public void AddUser(User entity) {
-      ExecuteWithContext((context) => {
-        context.Users.Add(entity);
-        context.SaveChanges();
-      });
-    }
-
-    public void UpdateUser(User entity) {
-      ExecuteWithContext((context) => {
-        context.Users.Attach(entity);
-        context.Entry(entity).State = System.Data.EntityState.Modified;
-        context.SaveChanges();
-      });
+    public void InsertOrUpdateUser(User entity) {
+      using (var context = CreateContext()) {
+        throw new NotImplementedException();
+      }
     }
 
     void DeleteUser(User entity) {
-      ExecuteWithContext((context) => {
-        context.Users.Remove(entity);
-      });
+      using (var context = CreateContext()) {
+        throw new NotImplementedException();
+      }
     }
 
@@ -212,7 +156,7 @@
 
     public UsageRecord FindUsageRecordById(long id) {
-      return ExecuteWithContext<UsageRecord>((context) => {
+      using (var context = CreateContext()) {
         return context.UsageRecords.FirstOrDefault(prod => prod.ProductId == id);
-      });
+      }
     }
 
@@ -231,34 +175,26 @@
     }
 
-    public void AddUsageRecord(UsageRecord entity) {
-      ExecuteWithContext((context) => {
-        context.UsageRecords.Add(entity);
+    public void InsertOrUpdateUsageRecord(UsageRecord entity) {
+      using (var context = CreateContext()) {
+        throw new NotImplementedException();
+      }
+    }
+
+    void DeleteUsageRecord(UsageRecord entity) {
+      using (var context = CreateContext()) {
+        throw new NotImplementedException();
+      }
+    }
+
+    #endregion
+
+    #region Invoice Methods
+
+    public void InsertOrUpdateInvoice(Invoice entity) {
+      using (var context = CreateContext()) {
+        context.Invoices.Add(entity);
+        context.ApplyStateChanges();
         context.SaveChanges();
-      });
-    }
-
-    public void UpdateUsageRecord(UsageRecord entity) {
-      ExecuteWithContext((context) => {
-        context.UsageRecords.Attach(entity);
-        context.Entry(entity).State = System.Data.EntityState.Modified;
-        context.SaveChanges();
-      });
-    }
-
-    void DeleteUsageRecord(UsageRecord entity) {
-      ExecuteWithContext((context) => {
-        context.UsageRecords.Remove(entity);
-      });
-    }
-
-    #endregion
-
-    #region Invoice Methods
-
-    public void AddInvoice(Invoice entity) {
-      ExecuteWithContext((context) => {
-        context.Invoices.Add(entity);
-        context.SaveChanges();
-      });
+      }
     }
 
Index: /branches/OaaS/HeuristicLab.Services.Optimization.Billing/HeuristicLab.Services.Optimization.Billing.csproj
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Optimization.Billing/HeuristicLab.Services.Optimization.Billing.csproj	(revision 9644)
+++ /branches/OaaS/HeuristicLab.Services.Optimization.Billing/HeuristicLab.Services.Optimization.Billing.csproj	(revision 9645)
@@ -59,8 +59,11 @@
     <Compile Include="Interfaces\IGenericDao.cs" />
     <Compile Include="Interfaces\IInvoiceFormattingEngine.cs" />
+    <Compile Include="Interfaces\IObjectWithState.cs" />
     <Compile Include="Interfaces\IOptimizationBilling.cs" />
     <Compile Include="Business\MockupBillingService.cs" />
     <Compile Include="Model\Model.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="Utils\DbContextUtil.cs" />
+    <Compile Include="Utils\StateUtil.cs" />
   </ItemGroup>
   <ItemGroup>
Index: /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Interfaces/IObjectWithState.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Interfaces/IObjectWithState.cs	(revision 9645)
+++ /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Interfaces/IObjectWithState.cs	(revision 9645)
@@ -0,0 +1,16 @@
+﻿
+namespace HeuristicLab.Services.Optimization.Billing.Interfaces {
+  // Interface that determines the current state of the entity
+  // Model classes implement this interface
+  // Importatnt: client application is responsible for setting the correct state
+  public interface IObjectWithState {
+    State EntityState { get; set; }
+  }
+
+  public enum State {
+    Added,
+    Unchanged,
+    Modified,
+    Deleted
+  }
+}
Index: /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Interfaces/IOptimizationBilling.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Interfaces/IOptimizationBilling.cs	(revision 9644)
+++ /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Interfaces/IOptimizationBilling.cs	(revision 9645)
@@ -23,4 +23,5 @@
 
     IList<Invoice> GetInvoices(string userName);
+    void SaveInvoice(Invoice invoice);
 
     User GetUser(string userName);
Index: /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Model/Model.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Model/Model.cs	(revision 9644)
+++ /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Model/Model.cs	(revision 9645)
@@ -2,4 +2,5 @@
 using System;
 using System.Collections.Generic;
+using HeuristicLab.Services.Optimization.Billing.Interfaces;
 namespace HeuristicLab.Services.Optimization.Billing.Model {
 
@@ -14,5 +15,5 @@
    */
 
-  public class ContactInformation {
+  public class ContactInformation : IObjectWithState {
     public long ContactInformationId { get; set; }
     public string OrganizationName { get; set; }
@@ -24,7 +25,11 @@
     public string FirstName { get; set; }
     public string Email { get; set; }
+
+    // Property is not mapped
+    // It is used to track state (disconnected entities)
+    public State EntityState { get; set; }
   }
 
-  public class PaymentInformation {
+  public class PaymentInformation : IObjectWithState {
     public long PaymentInformationId { get; set; }
     public long UserId { get; set; }
@@ -39,4 +44,6 @@
       set { PaymentMethodValue = (int)value; }
     }
+
+    public State EntityState { get; set; }
   }
 
@@ -60,5 +67,5 @@
   }
 
-  public class Product {
+  public class Product : IObjectWithState {
     public long ProductId { get; set; }
     public string Name { get; set; }
@@ -66,7 +73,9 @@
     public string ProductType { get; set; }
     public double Price { get; set; }
+
+    public State EntityState { get; set; }
   }
 
-  public class User {
+  public class User : IObjectWithState {
     public long UserId { get; set; }
     public long ContactInformationId { get; set; }
@@ -75,4 +84,6 @@
     public virtual IList<PaymentInformation> PaymentInformation { get; set; }
     public virtual ContactInformation ContactInformation { get; set; }
+
+    public State EntityState { get; set; }
   }
 
@@ -85,5 +96,5 @@
   }
 
-  public class Order {
+  public class Order : IObjectWithState {
     public long OrderId { get; set; }
     public long UserId { get; set; }
@@ -112,7 +123,9 @@
       set { BillingPeriodValue = (int)value; }
     }
+
+    public State EntityState { get; set; }
   }
 
-  public class OrderLine {
+  public class OrderLine : IObjectWithState {
     public long OrderLineId { get; set; }
     public long OrderId { get; set; }
@@ -123,4 +136,6 @@
     public virtual Order Order { get; set; }
     public virtual Product Product { get; set; }
+
+    public State EntityState { get; set; }
   }
 
@@ -129,5 +144,5 @@
   }
 
-  public class Invoice {
+  public class Invoice : IObjectWithState {
     public long InvoiceId { get; set; }
     public long UserId { get; set; }
@@ -148,7 +163,9 @@
       set { StatusValue = (int)value; }
     }
+
+    public State EntityState { get; set; }
   }
 
-  public class InvoiceLine {
+  public class InvoiceLine : IObjectWithState {
     public long InvoiceLineId { get; set; }
     public long InvoiceId { get; set; }
@@ -159,7 +176,9 @@
     public virtual Invoice Invoice { get; set; }
     public virtual Product Product { get; set; }
+
+    public State EntityState { get; set; }
   }
 
-  public class UsageRecord {
+  public class UsageRecord : IObjectWithState {
     public long UsageRecordId { get; set; }
     public long UserId { get; set; }
@@ -172,4 +191,6 @@
     public virtual User User { get; set; }
     public virtual Product Product { get; set; }
+
+    public State EntityState { get; set; }
   }
 }
Index: /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Utils/DbContextUtil.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Utils/DbContextUtil.cs	(revision 9645)
+++ /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Utils/DbContextUtil.cs	(revision 9645)
@@ -0,0 +1,13 @@
+﻿using System.Data.Entity;
+using HeuristicLab.Services.Optimization.Billing.Interfaces;
+
+namespace HeuristicLab.Services.Optimization.Billing.Utils {
+  public static class DbContextUtil {
+    public static void ApplyStateChanges(this DbContext context) {
+      foreach (var entry in context.ChangeTracker.Entries<IObjectWithState>()) {
+        IObjectWithState stateInfo = entry.Entity;
+        entry.State = StateUtil.ConvertState(stateInfo.EntityState);
+      }
+    }
+  }
+}
Index: /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Utils/StateUtil.cs
===================================================================
--- /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Utils/StateUtil.cs	(revision 9645)
+++ /branches/OaaS/HeuristicLab.Services.Optimization.Billing/Utils/StateUtil.cs	(revision 9645)
@@ -0,0 +1,19 @@
+﻿using System.Data;
+using HeuristicLab.Services.Optimization.Billing.Interfaces;
+
+namespace HeuristicLab.Services.Optimization.Billing.Utils {
+  public static class StateUtil {
+    public static EntityState ConvertState(State state) {
+      switch (state) {
+        case State.Added:
+          return EntityState.Added;
+        case State.Deleted:
+          return EntityState.Deleted;
+        case State.Modified:
+          return EntityState.Modified;
+        default:
+          return EntityState.Unchanged;
+      }
+    }
+  }
+}
