In the code sample, the chart of account model is stored in a json string. The function processjson - deseralizes the json string into a chartOfAcct class object. Using the base class, I select by predicate the object number resulting in a match. This match is the only object that can be updated by entity framework! The Match chartOfAcct from the database is stored in a IQueryable variable called query.
The json string object variable called chartOfAcct is mapped into a business view using the abstract factory called view. View is mapped into the entity framework retrieved by base GetObjectsAsync using the Abstract Factory. I use a list and a index to reference the base chartOfacct object because foreach will not allow item to be passed by reference.
class ChartOfAccountRepository : Repository<ChartOfAcct>
public class ChartOfAccountRepository : Repository<ChartOfAcct> { private Entities _dbContext; private ApplicationViewFactory applicationViewFactory; public ChartOfAccountRepository(DbContext db) : base(db) { _dbContext = (Entities)db; applicationViewFactory = new ApplicationViewFactory(); } public void ProcessAccount(string json) { ChartOfAcct chartOfAcct = JsonConvert.DeserializeObject<ChartOfAcct>(json); Task<Company> companyTask = (from e in _dbContext.Companies where e.CompanyId == chartOfAcct.CompanyId select e).FirstOrDefaultAsync<Company>(); chartOfAcct.Company = companyTask.Result; ChartOfAccountView view = applicationViewFactory.MapChartOfAccountView(chartOfAcct); IQueryable<ChartOfAcct> query = GetObjectsAsync(e=>e.ObjectNumber == view.ObjectNumber, ""); List<ChartOfAcct> list = query.ToList<ChartOfAcct>(); if (list.Count==0) { AddObject(chartOfAcct); } else { //foreach (var item in query) for (int i = 0; i < (int) list.Count; i++) { var item = list[i]; applicationViewFactory.MapChartOfAccountEntity(ref item, view); UpdateObject(item); } } }
Json String
public bool CreateAssets() { string json = ""; json = @"{ ""Location"":""01"" ,""BusUnit"":""1200"",""Account"":""1200.100"" ,""Description"":""Assets (DB)"",""CompanyNumber"":""1000"",""ObjectNumber"":""100"" ,""CompanyId"":1,""Level"":0,""PostEditCode"":""P""}"; ProcessAccount(json); return true; }
Repository<T> where T : class Unit of Work Base
public void UpdateObject(T dataObject) { { _dbContext.Entry(dataObject).State = System.Data.Entity.EntityState.Modified; }