public IQueryResult <TEntity> Write(IQuery <TEntity> query) { try { CreateIfNotExists(typeof(TEntity).Name); lock (_lock) { if (query.ActionType == ActionType.Select) { throw new InvalidOperationException(); } using (var transaction = new Transaction(FilePath, null)) { Source = transaction.ReadStream(); transaction.BackUp(); } var lines = Source.Split(Line).Where(x => x != "\r\n" && !string.IsNullOrEmpty(x)).ToArray(); if (query.ActionType == ActionType.Delete) { if (string.IsNullOrEmpty(Source)) { throw new ArgumentNullException("Source"); } if (query.Keys == null) { throw new ArgumentNullException("Keys"); } Modified = lines.Where( x => query.Keys.Contains(Convert.ToInt32(x.Substring(0, x.IndexOf(Field)))) == false) .ToArray(); Modified = Modified.Select(x => x + $"{Line}").ToArray(); return(new QueryResult <TEntity>() { IsSuccess = true, ServiceInfo = new TransactionServiceInfo() { FilePath = FilePath, Modified = Modified } }); } if (query.ActionType == ActionType.Add) { if (query.Entities == null) { throw new ArgumentNullException("Entities"); } int maxId = 0; if (lines.Length > 0) { var lstLine = lines.Last(); maxId = Convert.ToInt32(lstLine.Substring(0, lstLine.IndexOf(Field))); } Modified = lines.Concat(_interpreter.InterpreteToString(query.Entities, maxId)).ToArray(); Modified = Modified.Select(x => x + $"{Line}").ToArray(); return(new QueryResult <TEntity>() { IsSuccess = true, Result = query.Entities, ServiceInfo = new TransactionServiceInfo() { FilePath = FilePath, Modified = Modified } }); } if (query.ActionType == ActionType.Update) { if (string.IsNullOrEmpty(Source)) { throw new ArgumentNullException("Source"); } if (query.Entities == null) { throw new ArgumentNullException("Entities"); } var updates = _interpreter.InterpreteToString(query.Entities); Modified = lines.ToArray(); for (int i = 0; i < Modified.Length; i++) { int id = Convert.ToInt32(Modified[i].Substring(0, Modified[i].IndexOf(Field))); if (updates.ContainsKey(id)) { Modified[i] = updates[id]; } } Modified = Modified.Select(x => x + $"{Line}").ToArray(); return(new QueryResult <TEntity>() { IsSuccess = true, Result = query.Entities, ServiceInfo = new TransactionServiceInfo() { FilePath = FilePath, Modified = Modified } }); } throw new NullReferenceException(); } } catch (Exception exception) { using (var transaction = new Transaction(FilePath, null)) { transaction.RollBack(); } return(new QueryResult <TEntity>() { IsSuccess = false, Exception = exception, ErrorMessage = exception.Message, ServiceInfo = new TransactionServiceInfo() { FilePath = FilePath, Modified = Modified } }); } }